Debian Codegraph @

node/rxjs/src/internal/operators/reduce.ts

raw
1 import { scanInternals } from './scanInternals';
2 import { OperatorFunction } from '../types';
3 import { operate } from '../util/lift';
4
5 export function reduce<V, A = V>(accumulator: (acc: A | V, value: V, index: number) => A): OperatorFunction<V, V | A>;
6 export function reduce<V, A>(accumulator: (acc: A, value: V, index: number) => A, seed: A): OperatorFunction<V, A>;
7 export function reduce<V, A, S = A>(accumulator: (acc: A | S, value: V, index: number) => A, seed: S): OperatorFunction<V, A>;
8
9 /**
10 * Applies an accumulator function over the source Observable, and returns the
11 * accumulated result when the source completes, given an optional seed value.
12 *
13 * <span class="informal">Combines together all values emitted on the source,
14 * using an accumulator function that knows how to join a new source value into
15 * the accumulation from the past.</span>
16 *
17 * ![](reduce.png)
18 *
19 * Like
20 * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),
21 * `reduce` applies an `accumulator` function against an accumulation and each
22 * value of the source Observable (from the past) to reduce it to a single
23 * value, emitted on the output Observable. Note that `reduce` will only emit
24 * one value, only when the source Observable completes. It is equivalent to
25 * applying operator {@link scan} followed by operator {@link last}.
26 *
27 * Returns an Observable that applies a specified `accumulator` function to each
28 * item emitted by the source Observable. If a `seed` value is specified, then
29 * that value will be used as the initial value for the accumulator. If no seed
30 * value is specified, the first item of the source is used as the seed.
31 *
32 * ## Example
33 *
34 * Count the number of click events that happened in 5 seconds
35 *
36 * ```ts
37 * import { fromEvent, takeUntil, interval, map, reduce } from 'rxjs';
38 *
39 * const clicksInFiveSeconds = fromEvent(document, 'click')
40 * .pipe(takeUntil(interval(5000)));
41 *
42 * const ones = clicksInFiveSeconds.pipe(map(() => 1));
43 * const seed = 0;
44 * const count = ones.pipe(reduce((acc, one) => acc + one, seed));
45 *
46 * count.subscribe(x => console.log(x));
47 * ```
48 *
49 * @see {@link count}
50 * @see {@link expand}
51 * @see {@link mergeScan}
52 * @see {@link scan}
53 *
54 * @param accumulator The accumulator function called on each source value.
55 * @param seed The initial accumulation value.
56 * @return A function that returns an Observable that emits a single value that
57 * is the result of accumulating the values emitted by the source Observable.
58 */
59 export function reduce<V, A>(accumulator: (acc: V | A, value: V, index: number) => A, seed?: any): OperatorFunction<V, V | A> {
60 return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
61 }