Skip to content

V2: utils: fold()

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

(Since 2.2.0)

fold() takes and combines values using a reduce function supplied by a user. When a stream is ended, fold() passes through a single value: the last value of an accumulator. The functionality is similar to Array.prototype.reduce().

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

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

Factory function: fold(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: fold.Constructor

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

Static property: fold.Constructor.make

An alias to fold. Useful with metaprogramming.

Examples

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

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