BACK
Reference · 10

scan

Accumulates a value and emits the intermediate results.

Signature

scan(accumulator: (acc: R, value: T, index: number) => R, seed?: R): OperatorFunction

Marble diagram

in:    --1--2--3--|
scan+: --1--3--6--|

What it does

Works like Array.reduce, but emits the accumulator after every next. It's the perfect building block for deriving local state from a stream of events.

When to use

Counters (clicks, progress), accumulating a list of items, small state machines, a reactive equivalent of a Redux reducer: action$.pipe(scan(reducer, initialState)).

Gotcha

Without a seed, the first accumulator is the first value, and the result type is limited to T. For an accumulator of a different type, always pass a seed.

See also

reduce, map, distinctUntilChanged

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...