Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created October 14, 2012 20:22
Show Gist options
  • Save abozhilov/3889708 to your computer and use it in GitHub Desktop.
Save abozhilov/3889708 to your computer and use it in GitHub Desktop.
Set-builder based times
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