Adding _.count to count truthy values in an iterator. _.count([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; }) = 3

This commit is contained in:
Samuel Clay
2011-04-05 18:09:47 -04:00
parent a9ac8b11f8
commit c8e3c04076
3 changed files with 34 additions and 6 deletions

View File

@@ -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`.