It is beyond anything you have ever experienced or imagined
Useful JavaScript Extensions: Number#times
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 <code>this</code> 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); });
| Print article | This entry was posted by Daniel X Moore on August 31, 2010 at 11:24 am, and is filed under 256 JavaScript Game Extensions, Game Development, Programming. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

