Skip to content

reduceLazy() function

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

Signature:

typescript
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>;

Example

Type must be provided for stand alone call.

ts
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

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

You can use asynchronous callback

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

AsyncIterable doesn't matter.

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

Open Source Code

Released under the Apache-2.0 License.