Skip to content

Instantly share code, notes, and snippets.

@AutoSponge
Last active October 12, 2015 20:18
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 AutoSponge/4081985 to your computer and use it in GitHub Desktop.
Save AutoSponge/4081985 to your computer and use it in GitHub Desktop.
an each implementation that caches unraveled loops
var each = (function () {
function each(arr, fn) {
var len = arr.length;
return (each[len] || (each[len] = each.factory(len), each[len]))(arr, fn);
}
each.factory = function (len) {
var body = "\tvar i = 0;\n";
while (len--) {
body += "\tfn(i, arr[i++]);\n";
}
body += "\treturn;\n";
return Function("arr", "fn", body);
};
return each;
}());
each([1,2,3,4], function (i, e) {console.log(e + 1);});
//performs almost as fast as for loops in chrome
//fastest looper in IE: http://jsperf.com/jquery-each-vs-for-loop/162
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment