Created
April 23, 2012 22:05
-
-
Save benvinegar/2474195 to your computer and use it in GitHub Desktop.
Superfast JavaScript forEach function
This file contains hidden or 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
function forEach(arr, fn) { | |
var impl = fn.toString(); | |
var m = impl.match(/function \((\w+),?\s*(\w+)?\) { (.*) }/); | |
var arg0 = m[1]; | |
var arg1 = m[2]; | |
var body = m[3]; | |
var program = []; | |
program.push('var ' + arg0 + ';'); | |
if (arg1) | |
program.push('var ' + arg1 + ';'); | |
var val; | |
for (var i = 0; i < arr.length; i++) { | |
val = arr[i]; | |
program.push(arg0 + ' = ' + val.toString() + ';'); | |
if (arg1) | |
program.push(arg1 + ' = ' + i + ';'); | |
program.push(body); | |
} | |
program = program.join(''); | |
console.log(program); | |
eval(program); | |
} | |
var arr = [1, 2, 3]; | |
forEach(arr, function(val, i) { arr[i] += 1; }); | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment