Skip to main content

reduceLazy

reduceLazy() function

High order functional version of reduce, which behaves identical to it.

Signature:
declare function reduceLazy<T>(f: AsyncReducer<T, T>, seed?: T): (iterable: Iterable<T> | AsyncIterable<T>) => Promise<T>;

declare function reduceLazy<T, Acc>(f: AsyncReducer<Acc, T>, seed: Acc): (iterable: Iterable<T> | AsyncIterable<T>) => Promise<Acc>;

declare function reduceLazy<T>(f: SyncReducer<T, T>, seed?: T): <C extends Iterable<T> | AsyncIterable<T>>(iterable: C) => ReturnValueType<C>;

declare function reduceLazy<T, Acc>(f: SyncReducer<Acc, T>, seed: Acc): <C extends Iterable<T> | AsyncIterable<T>>(iterable: C) => ReturnValueType<C, Acc>;

declare function reduceLazy<T extends Iterable<unknown> | AsyncIterable<unknown>, Acc>(f: SyncReducer<Acc, IterableInfer<T>> | AsyncReducer<Acc, IterableInfer<T>>, seed: Acc): (iterable: InferCarrier<T>) => ReturnValueType<T, Acc>;

declare function reduceLazy<T extends Iterable<unknown> | AsyncIterable<unknown>>(f: AsyncReducer<IterableInfer<T>, IterableInfer<T>> | SyncReducer<IterableInfer<T>, IterableInfer<T>>, seed?: IterableInfer<T>): (iterable: InferCarrier<T>) => ReturnValueType<T, IterableInfer<T>>;

Example

Type must be provided for stand alone call.

const reduce = reduceLazy((a: number, b: number) => a + b, 5)

reduce([1, 2, 3]) // number
reduce(toAsync([1, 2, 3])) // Promise<number>

Fit perfectly with pipe

pipe(
[1, 2, 3, 4],
reduceLazy((a, b) => a + b, 5)
); // 15

You can use asynchronous callback

await pipe(
[1, 2, 3, 4],
reduceLazy(async (a, b) => a + b, 5)
); // 15

AsyncIterable doesn't matter.

await pipe(
[1, 2, 3, 4],
toAsync,
reduceLazy((a, b) => a + b, 5)
); // 15