reactive.how 2.0-alpha Menu

reduce vs scan

❚ reduce takes the same three arguments as ❚ scan:

  • an input stream
  • an accumulator function (e.g. prepend a character to a string)
  • an initial value called seed (e.g. !)

reduce

  • The seed will be used as an initial acc (accumulation)
  • When the input stream emits an event value v:
    • v and the latest acc are given to the accumulator
    • The returned value will be used as the next acc
  • When the input stream completes, the output stream emits the last acc and completes

scan

  • The seed will be used as an initial acc (accumulation)
  • When the input stream emits an event value v:
    • v and the latest acc are given to the accumulator
    • The returned value is emitted and will be used as the next acc
  • When the input stream completes, the output stream completes

Learn more about scan ➜

Notes

As you can see, while ❚ scan returns a new stream of progressively accumulated values, ❚ reduce returns a new stream of, at most, one value. At most? If the input stream never completes, ❚ reduce will never emit any value on the output stream.

Ultimately, ❚ reduce is equivalent to ❚ scan chained with ❚ takeLast(1).

See also


takeLast vs take


count


accumulator


The JavaScript pipeline operator proposal

💌 I create something new each week!
Learn Reactive Programming and stay tuned.

Occasional updates, plus:

Cédric Soulas - Freelance Developer Advocate. Learn more.

Follow 👨‍💻 Hire me

News

@CedricSoulas