Last active
October 20, 2015 00:20
-
-
Save amcmillan01/99a996c1cfa7d0ddfd7c to your computer and use it in GitHub Desktop.
adds a `each` method to a data collection that's use for iteration over the data (array or objects)
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
/** | |
* adds a `each` method to a data collection that's use for iteration over the data (array or objects) | |
* @param {array|object} collection | |
* @example | |
* var c = eachify(['a', 'b', 'c']); | |
* c.each(function(item, i) { | |
* console.log('index=' + i, 'value=' + item); | |
* }); | |
* | |
* @example | |
* var d = eachify({a: 'A', foo: 'Bar', cat: 'Meow?'}); | |
* d.each(function(item, i) { | |
* console.log('property=' + i, 'value=' + item); | |
* }); | |
* | |
* @return {array|object} collection | |
*/ | |
var eachify = function(collection) { | |
var each; | |
// array | |
if (collection.hasOwnProperty('length')) { | |
each = function(fn) { | |
for (var i = 0; i < collection.length; i++) { | |
fn(collection[i], i); | |
} | |
}; | |
} | |
// object | |
else { | |
each = function(fn) { | |
for (var p in collection) { | |
if (p !== 'each') { | |
fn(collection[p], p); | |
} | |
} | |
}; | |
} | |
collection.each = each; | |
return collection; | |
}; | |
//var c = eachify(['a', 'b', 'c']); | |
//c.each(function(item, i) { | |
// console.log('index=' + i, 'value=' + item); | |
//}); | |
// | |
//console.log('------------'); | |
// | |
//var d = eachify({a: 'A', foo: 'Bar', cat: 'Meow?'}); | |
//d.each(function(item, i) { | |
// console.log('property=' + i, 'value=' + item); | |
//}); | |
// output --- | |
// index=0 value=a | |
// index=1 value=b | |
// index=2 value=c | |
// ------------ | |
// property=a value=A | |
// property=foo value=Bar | |
// property=cat value=Meow? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment