is used to perform an accumulation operation on the values emitted by an observable sequence. It resembles the Array.prototype.reduce()
operator takes an accumulator function and an optional seed value as its parameters. The accumulator function is called for each value emitted by the source observable, and it accumulates the intermediate result based on the previous accumulated value and the current value from the source. The accumulated value is then emitted to the resulting observable sequence.
Here's the general syntax of the scan operator:
const $scanOperator = from([1,2,3,4]).pipe(
scan((sum,num) => sum+num)
console.log('scan operator data', data);
// output :
// scan operator data 1
// scan operator data 3
// scan operator data 6
// scan operator data 10
In scan operator, intermediate result is emitted while in reduce operator intermediate result is not emitted and only the final result is emitted.
The scan operator is useful for scenarios where you need to maintain state or accumulate values over time, such as tracking the total count, calculating averages, or simulating a running total.