Skip to content

V2: utils: asFun()

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

(Since 2.2.0) It is a utility to build pipelines from a list of functions (including asynchronous ones, generators, and asynchronous generators) bypassing the streaming framework and packaging it as an asynchronous function, which can work on Node 8 and up.

If your target is Node 10 and up, you may consider asGen(), which wraps everything in an asynchronous generator.

asFun(...fns)

This is the main function of the module. It takes functions as arguments and builds a pipeline connecting them. The result is presented as an asynchronous function, which can return:

  • none when no result was produced.
  • a value wrapped in many() for multiple results.
  • any other value for a singular as-is value.

The first argument can be an iterator object or an asynchronous iterator object, which serves as a source of data. Usually, in this case, the returned function is called without a value (because it will be ignored anyway).

const {chain, none, final} = require('stream-chain');
const {asFun} = require('stream-chain/utils/asFun');

const pipeline = asFun(
  x => x % 2 == 0 ? none : x,
  x => x === 1 ? final(1) : x;
  x => x * x
);

// in async context:
const data = [1, 2, 3, 4, 5];
for (const value of data) {
  const result = await pipeline(value);
  if (result === none) continue;
  console.log(result);
}
// 1, 9, 25

Notes

Internally asFun() uses next(value, fns, index, push) described below collecting all possible values into an internal array. So if a call to a generated pipeline can potentially produce a lot of value that can impact the memory usage consider using asGen(), which doesn't have this limitation. Alternatively, you can devise a way to use next(value, fns, index, push) directly redirecting push to a proper function to avoid collecting data in memory.

Static properties

The following static properties are available:

  • next(value, fns, index, push)

All of them are documented below.

Additionally, the following properties are imported from defs module:

  • none,
  • final(value),
  • isFinal(value),
  • getFinalValue(value),
  • many(array).
  • isMany(value),
  • getManyValues(value)

Presently all these properties are documented in defs.

next(value, fns, index, push)

This is the workhorse of the module. It takes the following arguments:

  • value — any suitable value for a processing.
  • fns — an array of functions to pass value through. It can be any functions including asynchronous ones, generators, or asynchronous generators.
  • index — a non-negative integer value, which serves an index in fns to start the processing from. Usually, it is used for recursive calls, while users start processing from 0.
  • push — a function that takes one processed value.

next() does not return a value. Instead, it uses push() to accumulate potential multiple values.

Clone this wiki locally