diff --git a/test/objects.js b/test/objects.js index 02e00abd1..71e46bdb6 100644 --- a/test/objects.js +++ b/test/objects.js @@ -17,7 +17,7 @@ $(document).ready(function() { "indexOf", "inject", "intersect", "invoke", "isArguments", "isArray", "isDate", "isElement", "isEmpty", "isEqual", "isFunction", "isNaN", "isNull", "isNumber", "isRegExp", "isString", "isUndefined", "keys", "last", "lastIndexOf", "map", "max", "methods", "min", "noConflict", "pluck", "range", "reduce", "reduceRight", "reject", "rest", "select", - "size", "some", "sortBy", "sortedIndex", "tail", "tap", "template", "toArray", "uniq", + "size", "some", "sortBy", "sortedIndex", "tail", "tap", "template", "times", "toArray", "uniq", "uniqueId", "values", "without", "wrap", "zip"]; ok(_(expected).isEqual(_.methods(_)), 'provides a sorted list of functions'); var obj = {a : 'dash', b : _.map, c : (/yo/), d : _.reduce}; diff --git a/test/utility.js b/test/utility.js index 763a48036..b006dee32 100644 --- a/test/utility.js +++ b/test/utility.js @@ -29,6 +29,17 @@ $(document).ready(function() { while(i++ < 100) ids.push(_.uniqueId()); equals(_.uniq(ids).length, ids.length, 'can generate a globally-unique stream of ids'); }); + + test("utility: times", function() { + var vals = []; + _.times(3, function (i) { vals.push(i); }); + ok(_.isEqual(vals, [0,1,2]), "is 0 indexed"); + // + vals = []; + _(3).times(function (i) { vals.push(i); }); + ok(_.isEqual(vals, [0,1,2]), "works as a wrapper"); + }); + test("utility: template", function() { var basicTemplate = _.template("<%= thing %> is gettin' on my noives!"); diff --git a/underscore.js b/underscore.js index 6c120a772..cf6a1578e 100644 --- a/underscore.js +++ b/underscore.js @@ -589,6 +589,13 @@ _.identity = function(value) { return value; }; + + // run a function n times. + // looks good in wrapper form: + // _(3).times(alert) + _.times = function (n, fn, context) { + for (var i=0; i < n; i++) fn.call(context, i) + }; // Break out of the middle of an iteration. _.breakLoop = function() {