Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active December 12, 2015 03:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSDK/4705577 to your computer and use it in GitHub Desktop.
Save JustinSDK/4705577 to your computer and use it in GitHub Desktop.
The Example of "JavaScript Essence: Writing a Utility Library"

The Example of JavaScript Essence: Writing a Utility Library

(function(global) {
    var XD = {
        trim: function(text) {
            return (text || '').replace( /^(\s|\u00A0)+|(\s|\u00A0)+$/g, '');
        },
        isArray: function(obj) {
            return Object.prototype.toString.call(obj) === '[object Array]';
        },
        isFunction: function(obj) {
            return Object.prototype.toString.call(obj) === '[object Function]';
        },
        each: function(obj, callback) {
            var length = obj.length,
                isObj = (length === undefined) || this.isFunction(obj);
            if (isObj) {
                for(var name in obj) {
                    if(callback.call(obj[name], obj[name], name) === false ) {
                        break;
                    }
                }
            }
            else {
                for(var i = 0, value = obj[0];
                    i < length && callback.call(obj[i], value, i) !== false;
                    value = obj[++i] ) {}
            }
            return obj;
        },
        makeArray: function(arrayLike) {
            if(arrayLike.length != null) {
                return Array.prototype.slice.call(arrayLike, 0)
                        .filter(function(ele) { return ele !== undefined; });
            }
            return [];
        }
    };
    global.XD = XD;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment