Last active
October 12, 2015 20:18
-
-
Save AutoSponge/4081985 to your computer and use it in GitHub Desktop.
an each implementation that caches unraveled loops
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
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