Created
May 16, 2013 13:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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