Skip to content

V2: utils: Reduce

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

(Since 2.2.0)

Reduce takes and combines them using a reduce function supplied by a user. Its accumulator is publicly accessible as accumulator property. The functionality is similar to Array.prototype.reduce().

It is returned by require('stream-chain/utils/Reduce') and it is based on Writable. Being Writable it always terminates a pipeline and do not produce any items.

Check out its sister utilities: fold() and scan(). API-wise it is very similar to fold().

Constructor: Reduce(options)

It takes options and returns a Writable stream.

options can be one of these:

  • an object detailed in the Node's documentation.
    • objectMode 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.

Public property: accumulator

It is a property, which represents an accumulator. Its initial value is specified by initial described above. It is updated with every new item coming from a pipeline with reducer described above.

Static property: Reduce.reduce(options, initial)

A factory function to construct an instance of Reduce. The first argument can be an object, which is used as options described above to call a constructor. In this case, the second argument is ignored. Otherwise, the first argument is assumed to be a reducer function and the second argument is initial both described above.

const Reduce = require('stream-chain/utils/Reduce');
const r1 = new Reduce({reducer: (acc, value) => acc + value, initial: 0});

// identical to:

const {reduce} = require('stream-chain/utils/Reduce');
const r2 = reduce((acc, value) => acc + value, 0);

Static property: Reduce.make

An alias to Reduce.reduce. Useful with metaprogramming.

Static property: Reduce.make.Constructor

An alias to Reduce. Useful with metaprogramming.

Examples

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

const r = new Reduce({reducer: (acc, value) => acc + value, initial: 0});

const pipeline = chain([
  // ... the rest of the pipeline
  r
]);
// input: 1, 2, 3, 4, 5

r.on('finish', () => {
  console.log(r.accumulator);
  // output: 15
});