Skip to content

V2: utils: scan()

Eugene Lazutkin edited this page Aug 3, 2022 · 1 revision

(Since 2.2.0)

scan() takes and combines them using a reduce function supplied by a user passing through the latest (running) value of an accumulator unlike fold(), which passes it through only once when a stream ends.

It is returned by require('stream-chain/utils/scan') and it is based on Transform.

Check out its sister utilities: fold() and Reduce. API-wise it is a twin of fold().

Factory function: scan(options, initial)

It takes one or two arguments and returns a Transform stream.

options can be one of these:

  • an object detailed in the Node's documentation.
    • readableObjectMode and writableObjectMode are always set to `true.
    • The following custom options are recognized:
      • (optional) reducer is a function or an asynchronous function, which takes a current accumulator value and a current item and returns a new accumulator value. Default: (acc, value) => value.
      • (optional) initial is an initial value of an accumulator. Default: 0.
      • While both custom options above are marked as "optional" in reality they are rarely left to be defaults.
  • Otherwise, it is assumed to be a function, same as reducer described above.

The second argument initial is used only if options is a function. Otherwise, it is ignored. When used it is the initial described above.

Static property: scan.Constructor

A constructor of the underlying stream class produced by scan(). Useful to inspect objects with instanceof.

Static property: scan.Constructor.make

An alias to scan. Useful with metaprogramming.

Examples

const {chain} = require('stream-chain');
const scan = require('stream-chain/utils/scan');

const pipeline = chain([
  scan((acc, value) => acc + value, 0)
  // ... the rest of the pipeline
]);
// input:  1, 2, 3, 4, 5
// output: 1, 3, 6, 10, 15
Clone this wiki locally