Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The missing JS utils #1

Open
morlandi opened this issue Sep 30, 2020 · 0 comments
Open

The missing JS utils #1

morlandi opened this issue Sep 30, 2020 · 0 comments

Comments

@morlandi
Copy link
Owner

Decide where to place these javascript utilities:

window.Utils = (function() {

    function getCookie(name) {
        var value = '; ' + document.cookie,
            parts = value.split('; ' + name + '=');
        if (parts.length == 2) return parts.pop().split(';').shift();
    }

    function lookup_queryset(qs, model, pk) {
    /*
        Find a specific record into serialized queryset;
    */
        var obj = null;
        $.each(qs, function(index, value) {
            if (value.pk == pk && value.model == model) {
                obj = value;
                return false;
            }
        });
        return obj;
    }

    // Speed up calls to hasOwnProperty
    var hasOwnProperty = Object.prototype.hasOwnProperty;

    // http://stackoverflow.com/questions/4994201/is-object-empty
    function isEmptyObject(obj) {

        // null and undefined are "empty"
        if (obj == null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // If it isn't an object at this point
        // it is empty, but it can't be anything *but* empty
        // Is it empty?  Depends on your application.
        if (typeof obj !== "object") return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
            if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;
    }


    // Find an Object by attribute in an Array
    // http://stackoverflow.com/questions/5579678/jquery-how-to-find-an-object-by-attribute-in-an-array#19154349
    function lookup(array, prop, value) {
        for (var i = 0, len = array.length; i < len; i++)
            if (array[i] && array[i][prop] === value) return array[i];
        return null;
    }

    return {
        getCookie: getCookie,
        lookup_queryset: lookup_queryset,
        isEmptyObject: isEmptyObject,
        lookup: lookup
    };

})();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant