diff --git a/index.html b/index.html index 215d06a6a..a7d9c5284 100644 --- a/index.html +++ b/index.html @@ -137,12 +137,13 @@ each, map, reduce, reduceRight, detect, select, - reject, all, - any, include, - invoke, pluck, - max, min, - sortBy, sortedIndex, - toArray, size + reject, count, + all, any, + include, invoke, + pluck, max, + min, sortBy, + sortedIndex, toArray, + size

@@ -337,6 +338,16 @@ var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

 var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
 => [1, 3, 5]
+
+ +

+ count_.count(list, [iterator], [context]) +
+ Returns a count of elements which pass the truth test (iterator). +

+
+var count = _.count([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
+=> 3
 

diff --git a/test/collections.js b/test/collections.js index 442b205f1..b14821a9d 100644 --- a/test/collections.js +++ b/test/collections.js @@ -122,6 +122,13 @@ $(document).ready(function() { equals(odds.join(', '), '1, 3, 5', 'rejected each even number'); }); + test('collections: count', function() { + var count = _.count([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }); + equals(count, 3, 'counted even numbers'); + var count = _.count([0, 1, 2, 3, 4, 5, 6]); + equals(count, 6, 'counted all truthy numbers'); + }); + test('collections: all', function() { ok(_.all([]), 'the empty set'); ok(_.all([true, true, true]), 'all true values'); diff --git a/underscore.js b/underscore.js index 259a4f310..313b16c1e 100644 --- a/underscore.js +++ b/underscore.js @@ -164,6 +164,16 @@ return results; }; + // Returns a count of elements which pass a truth test. + _.count = function(obj, iterator, context) { + var count = 0; + iterator = iterator || _.identity; + each(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) count += 1; + }); + return count; + }; + // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`.