generated from jfarmer/template-javascript
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcount.js
32 lines (27 loc) · 809 Bytes
/
count.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Given an array and a function, returns the number of elements in array
* for which the returns true.
*
* @example
* count([1, 2, 3, 4, 5, 6], isEven); // => 3
*
* @param {any[]} collection - An array whose elements we want to count
* @param {function} predicate - A function that returns `true` or `false`
* @returns {number} The number of elements in `collection` for which `predicate`
* returns `true`
*/
function count(collection, predicate) {
let total = 0;
for (let item of collection) {
if (predicate(item)) {
total += 1;
}
}
return total;
}
if (require.main === module) {
console.log('Running sanity checks for count:');
// Add your own sanity checks here.
// How else will you be sure your code does what you think it does?
}
module.exports = count;