Created
April 23, 2012 08:10
-
-
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)
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
/* | |
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