Last active
August 29, 2015 14:05
-
-
Save alexhawkins/544dbe0631544c99861f to your computer and use it in GitHub Desktop.
Simplified Underscore .Each method
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
/* SIMPLIFIED UNDERSCORE .EACH method*/ | |
var _ = function(obj) { | |
if (obj instanceof _) return obj; | |
if (!(this instanceof _)) return new _(obj); | |
this._wrapped = obj; | |
}; | |
//context not typically neccessary, only needed if you want to pass some object (see example below) | |
var each = _.each = _.forEach = _.hansGruber = _.ferrisBueller = function(obj, iteration, context) { | |
//check to see if array | |
if (Array.isArray(obj)){ | |
//iterate through array | |
for (var i = 0; i < obj.length; i++) { | |
//call interation callback function for each element in the ojbect | |
iteration.call(context, obj[i], i, obj); | |
} | |
//then it must be a 'legit' object in that sense | |
} else { | |
//iterate through ojbect to get key | |
for (var key in obj) | |
iteration.call(context, obj[key], key, obj); | |
} | |
return obj; | |
}; | |
//tests | |
var arr = [1, 2, 4, 3]; | |
_.hansGruber(arr, function(el) { | |
console.log(el); | |
}); | |
var obj = { | |
year: 1918, | |
newsroom: 'The New York Times', | |
reason: 'For its public service in publishing in full so many official reports.' | |
}; | |
_.ferrisBueller(obj, function(el) { | |
console.log(el); | |
}); | |
var arr = [1, 2, 3]; | |
var myObj = { | |
foo: 5, | |
addFoo: function(el, i, lst) { | |
console.log(el + this.foo) | |
} | |
}; | |
_.hansGruber(arr, myObj.addFoo, myObj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When you're evaluating whether or not something is an array, try using
Array.isArray( obj )
. That's will returntrue
orfalse
.I'd advise you to change
iteration
toiterator
.