UNPKG

@lou.codes/iterables

Version:
25 lines (24 loc) 701 B
import { awaitableHandler } from "@lou.codes/utils"; import { forEach } from "./forEach.js"; /** * Reducer function for iterables and asynchronous iterables. * * @category Asynchronous Reducers * @example * ```typescript * const sum = Accumulator<number>(item => total => total + item); * const sumFrom0 = sum(0); * * sumFrom0([1, 2, 3]); // 6 * ``` * @param reducer Reducer function. * @returns Curried function with `reducer` in context. */ export const reduce = reducer => initialValue => iterable => { let accumulator = initialValue; return awaitableHandler(_ => accumulator)( forEach( async item => void (accumulator = await reducer(item)(accumulator)), )(iterable), ); };