Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active May 21, 2017 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/d3185f60999a560120a071733a64ff71 to your computer and use it in GitHub Desktop.
Save ccnokes/d3185f60999a560120a071733a64ff71 to your computer and use it in GitHub Desktop.
Pipe function, taken from twitter
// sync version
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
// example
const newFunc = pipe(fn1, fn2, fn3);
const result = newFunc(arg);
// async version
// take a series of promise producing functions and return a single promise
function asyncPipe(...promises) {
return function(initialVal) {
return promises.reduce(
(p, fn) => p.then(fn),
Promise.resolve(initialVal)
);
};
}
// example
async function inc(x) {
return x + 1;
}
const pipeAsync = asyncPipe(inc, inc, inc);
pipeAsync(1).then(console.log); //=> 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment