-
-
Notifications
You must be signed in to change notification settings - Fork 11
V2: utils: fold()
(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().
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
andwritableObjectMode
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.
-
(optional)
-
- 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.
A constructor of the underlying stream class produced by fold()
. Useful to inspect objects with instanceof
.
An alias to fold
. Useful with metaprogramming.
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