add #times utility method.

_(3).times(alert)

added tests and internal docs
This commit is contained in:
Mike Frawley
2010-02-17 10:21:59 -06:00
parent 263b1ee92d
commit 5a5e14d7a4
3 changed files with 19 additions and 1 deletions

View File

@@ -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};

View File

@@ -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!");

View File

@@ -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() {