Debian Codegraph @

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

raw
1 import { Observable } from '../Observable';
2 import { Subscriber } from '../Subscriber';
3 import { createOperatorSubscriber } from './OperatorSubscriber';
4
5 /**
6 * A basic scan operation. This is used for `scan` and `reduce`.
7 * @param accumulator The accumulator to use
8 * @param seed The seed value for the state to accumulate
9 * @param hasSeed Whether or not a seed was provided
10 * @param emitOnNext Whether or not to emit the state on next
11 * @param emitBeforeComplete Whether or not to emit the before completion
12 */
13
14 export function scanInternals<V, A, S>(
15 accumulator: (acc: V | A | S, value: V, index: number) => A,
16 seed: S,
17 hasSeed: boolean,
18 emitOnNext: boolean,
19 emitBeforeComplete?: undefined | true
20 ) {
21 return (source: Observable<V>, subscriber: Subscriber<any>) => {
22 // Whether or not we have state yet. This will only be
23 // false before the first value arrives if we didn't get
24 // a seed value.
25 let hasState = hasSeed;
26 // The state that we're tracking, starting with the seed,
27 // if there is one, and then updated by the return value
28 // from the accumulator on each emission.
29 let state: any = seed;
30 // An index to pass to the accumulator function.
31 let index = 0;
32
33 // Subscribe to our source. All errors and completions are passed through.
34 source.subscribe(
35 createOperatorSubscriber(
36 subscriber,
37 (value) => {
38 // Always increment the index.
39 const i = index++;
40 // Set the state
41 state = hasState
42 ? // We already have state, so we can get the new state from the accumulator
43 accumulator(state, value, i)
44 : // We didn't have state yet, a seed value was not provided, so
45
46 // we set the state to the first value, and mark that we have state now
47 ((hasState = true), value);
48
49 // Maybe send it to the consumer.
50 emitOnNext && subscriber.next(state);
51 },
52 // If an onComplete was given, call it, otherwise
53 // just pass through the complete notification to the consumer.
54 emitBeforeComplete &&
55 (() => {
56 hasState && subscriber.next(state);
57 subscriber.complete();
58 })
59 )
60 );
61 };
62 }