@monstermann/fn
Version:
A utility library for TypeScript.
24 lines (22 loc) • 599 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
//#region src/array/countBy.ts
/**
* `countBy(target, predicate)`
*
* Counts the number of elements in the `target` array satisfy the provided `predicate` function.
*
* ```ts
* const isEven = (n) => n % 2 === 0;
* countBy([1, 2, 3, 4, 5], isEven); // 2
* ```
*
* ```ts
* const isEven = (n) => n % 2 === 0;
* pipe([1, 2, 3, 4, 5], countBy(isEven)); // 2
* ```
*/
const countBy = dfdlT((target, predicate) => {
return target.reduce((acc, value, idx, target$1) => acc + (predicate(value, idx, target$1) ? 1 : 0), 0);
}, 2);
//#endregion
export { countBy };