Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 13x 6x 13x 16x 31x 16x | /**
* Calls a callback function for all the elements in an {@link Iterable}. The
* return value of the callback function is the accumulated result, and is
* provided as an argument in the next call to the callback function.
*
* Works like {@link Array.prototype.reduce}.
*
* @example
* Sum all numbers
* ```ts
* const sum = reduce((acc, curr) => acc + curr, 0);
* const result = sum([1, 2, 3]);
* console.log(result); // 6
* ```
*
* @see {@link filter}, {@link flatMap}, {@link map} and {@link sum} for
* similar operations.
*
* @typeParam T - the {@link Iterable} value type
* @typeParam U - the `reduce` result type
* @param reducerFn - the reducer Fucntion
* @param initialValue - the value for the first call of `reducerFn`
* @returns the reduced value
*/
export const reduce =
<T, U>(
reducerFn: (previousValue: U, currentValue: T) => U,
initialValue: U
) =>
(iterable: Iterable<T>, result = initialValue): U => {
for (const value of iterable) {
result = reducerFn(result, value);
}
return result;
};
|