Last active
May 21, 2017 02:06
-
-
Save ccnokes/d3185f60999a560120a071733a64ff71 to your computer and use it in GitHub Desktop.
Pipe function, taken from twitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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