Skip to content

Function: reduce()

reduce<T, A>(accumulator, seed): Operator<T, A>

Defined in: operators/reduce.ts:17

Creates a stream operator that accumulates all values from the source stream into a single value using a provided accumulator function.

This operator consumes the source lazily and emits intermediate values as phantoms. It will always emit at least the seed value if the stream is empty.

Type Parameters

T

T = any

The type of the values in the source stream.

A

A = any

The type of the accumulated value.

Parameters

accumulator

(acc, value) => CallbackReturnType<A>

Function combining current accumulated value with a new value. Can be synchronous or asynchronous.

seed

A

Initial value for the accumulator.

Returns

Operator<T, A>

An Operator instance usable in a stream's pipe method.

Examples

From reduce.spec.ts:12

typescript
let subject: ReturnType<typeof createSubject<number>> = createSubject<number>();

let source: Stream<number> = subject;

const accumulatedStream = source.pipe(reduce((acc, value) => acc + value, 0));
const results: number[] = [];
(async () => {
  for await (const value of eachValueFrom(accumulatedStream)) {
    results.push(value);
  }
})();
subject.next(1);
subject.next(2);
subject.next(3);
subject.complete();
await new Promise((resolve) => setTimeout(resolve, 100));
expect(results).toEqual([6]);

Released under the MIT License.