-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathcount_where.js
More file actions
38 lines (36 loc) · 1.24 KB
/
count_where.js
File metadata and controls
38 lines (36 loc) · 1.24 KB
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
33
34
35
36
37
38
import coerceToString from 'helper/string/coerce_to_string';
const reduce = Array.prototype.reduce;
/**
* Counts the characters in `subject` for which `predicate` returns truthy.
*
* @function countWhere
* @static
* @since 1.0.0
* @memberOf Count
* @param {string} [subject=''] The string to count characters.
* @param {Function} predicate The predicate function invoked on each character with parameters `(character, index, string)`.
* @param {Object} [context] The context to invoke the `predicate`.
* @return {number} Returns the number of characters for which `predicate` returns truthy.
* @example
* v.countWhere('hola!', v.isAlpha);
* // => 4
*
* v.countWhere('2022', function(character, index, str) {
* return character === '2';
* });
* // => 3
*/
export default function countWhere(subject, predicate, context) {
const subjectString = coerceToString(subject);
if (subjectString === '' || typeof predicate !== 'function') {
return 0;
}
const predicateWithContext = predicate.bind(context);
return reduce.call(
subjectString,
function(countTruthy, character, index) {
return predicateWithContext(character, index, subjectString) ? countTruthy + 1 : countTruthy;
},
0
);
}