Skip to content

Instantly share code, notes, and snippets.

@chrisjhoughton
Created May 16, 2013 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisjhoughton/5591675 to your computer and use it in GitHub Desktop.
Save chrisjhoughton/5591675 to your computer and use it in GitHub Desktop.
A tiny hacked together version of a few essential Underscore functions. Great for use in small scripts where you don't want to load the entire library.
// Setup the methods
var _ = {
init: function() {
var _this = this;
// Create the comparitor methods e.g. isString
this.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_this['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
},
each: function(obj, iterator, context) {
if (obj === null) return;
if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === {}) return;
}
} else {
for (var key in obj) {
if (obj[key]) {
if (iterator.call(context, obj[key], key, obj) === {}) return;
}
}
}
},
// Works on arrays
contains: function(array, target) {
var index = array.indexOf(target);
if (index === -1) {
return false;
} else {
return true;
}
},
isObject: function(obj) {
return obj === Object(obj);
},
isArray: function(obj) {
return toString.call(obj) == '[object Array]';
}
};
// Do some things on start (create isString, isFunction etc)
_.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment