Skip to content

Instantly share code, notes, and snippets.

@podgorniy
Created April 23, 2012 08:10
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 podgorniy/2469462 to your computer and use it in GitHub Desktop.
Save podgorniy/2469462 to your computer and use it in GitHub Desktop.
Universal iterator through arrays, array-like objects and objects. Now to run through data, you do not need to care about data representation (array or object)
/*
exaple of use
var data, processed;
data = [10,20,30,40];
processed = iterate(data, function (val, i) {
console.log(val);
});
data = {
masha : 10,
pasha : 20,
sasha : 30,
lesha : 40
};
processed = iterate(data, function (val, i) {
console.log(val);
});
*/
function iterate(list, func) {
var i, res;
if ( 'length' in list ) {
res = [];
for (i = 0; i < list.length; i += 1) {
res.push(func.call(list, list[i], i));
}
} else {
res = {};
for (i in list) {
res[i] = func.call(list, list[i], i);
}
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment