pipe-functions
Pipe functions in a Unix-like style. It supports Promises
(async) anywhere in the pipeline and every step will be executed sequentially. The return (resolve in case of Promises
) of each function will be passed in as an argument to the next one
Key features:
- Supports
Promises
, or any lib following the Promises/A+ spec about being thenable (.then() method) Promises
will be executed sequentially- First argument can be of any type (
String
, Number
, Date
, etc.) or even a Function
or a Promise
- Browser and Node.js ready
- Lightweight, 267 bytes (190 bytes gzipped)
Install
NPM / Node
npm install pipe-functions
Usage
Sync
const pipe = require('pipe-functions');
const result = pipe('input', fn1, fn2, fnN);
const result2 = pipe(fn0, fn1, fn2, fnN);
Async (Promises
)
If the pipeline contains a Promise
anywhere in the pipeline, we must treat pipe
like a Promise
itself, so we must to use .then() to get the final result.
const pipe = require('pipe-functions');
pipe('input', fn1, fnPromise1, fn2, fnPromise2).then(console.log);
Examples
OBS: Some examples needs a platform with support for Destructuring (Nodejs v6+, Chrome).
Sync
const pipe = require('pipe-functions');
const capitalize = v => v[0].toUpperCase() + v.slice(1);
const quote = v => `"${v}"`;
const result = pipe('time', capitalize, quote);
Async (Promises
)
const pipe = require('pipe-functions');
const capitalize = v => v[0].toUpperCase() + v.slice(1);
const fetchAndSetBandName = v => new Promise((resolve, reject) => setTimeout(() => resolve(`Pink Floyd - ${v}`), 1000));
pipe('time', capitalize, fetchAndSetBandName).then(console.log)
Example with destructuring,
To easily pass in more than one value (within an Object or Array) through the pipeline.
const pipe = require('pipe-functions');
const fetchBandName = ({ song }) => new Promise((resolve, reject) =>
setTimeout(() => resolve({ song, band: 'Pink Floyd' }), 1000));
const concatBandAndSong = ({ song, band }) => `${band} - ${song}`;
pipe('time', fetchBandName, concatBandAndSong).then(console.log)