Skip to content

Instantly share code, notes, and snippets.

@alexhawkins
Last active August 29, 2015 14:05
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 alexhawkins/544dbe0631544c99861f to your computer and use it in GitHub Desktop.
Save alexhawkins/544dbe0631544c99861f to your computer and use it in GitHub Desktop.
Simplified Underscore .Each method
/* 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);
@wulymammoth
Copy link

When you're evaluating whether or not something is an array, try using Array.isArray( obj ). That's will return true or false.

I'd advise you to change iteration to iterator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment