Part 5/256
For loops… I hate them so much. Fortunately, a well established functional iteration convention is the Number#times
method.
/**
* Calls iterator the specified number of times, passing in a number of the
* current iteration as a parameter. The number will be 0 on first call, 1 on
* second call, etc.
*
* @param {Function} iterator The iterator takes a single parameter, the number
* of the current iteration.
* @param {Object} [context] The optional context parameter specifies an object
* to treat as this
in the iterator block.
*
* @returns The number of times the iterator was called.
*/
Number.prototype.times = function(iterator, context) {
for(var i = 0; i < this; i++) {
iterator.call(context, i);
}
return i;
}
This hides the inner workings of the iteration from the calling code so there’s no need to keep track of an external dummy iterator variable if you don’t want to.
var n = 3; // Greets you three times, with respect n.times(function() { alert("O HAI!"); }); // logs: 0, 1, 2 n.times(function(i) { console.log(i); });