Created
October 14, 2012 20:22
-
-
Save abozhilov/3889708 to your computer and use it in GitHub Desktop.
Set-builder based times
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
function times(n, fn) { | |
var arr = []; | |
for (var i = 0; i < n; i++) { | |
var res = fn(i); | |
if (typeof res != 'undefined') { | |
arr.push(res); | |
} | |
} | |
return arr; | |
}; | |
//Execute the given function N times | |
times(5, function (i) { | |
console.log(i); | |
}); | |
//Initialize an array | |
var arr = times(10, function (i) { | |
return i; | |
}); | |
console.log(arr); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
//Initialize an array only with even numbers | |
var arr1 = times(10, function (i) { | |
if (i % 2 == 0) return i; | |
}); | |
console.log(arr1); //[0, 2, 4, 6, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment