Skip to content

Instantly share code, notes, and snippets.

@djfm
Last active September 23, 2016 13:24
Show Gist options
  • Save djfm/2ef93cc67283a4908f32fa31f75d2656 to your computer and use it in GitHub Desktop.
Save djfm/2ef93cc67283a4908f32fa31f75d2656 to your computer and use it in GitHub Desktop.
const chainStep = fn => (argSource, history) => {
if (argSource && (typeof argSource === 'object')) {
const then = argSource.then;
if (typeof then === 'function') {
return Promise.all(history).then(
settledHistory =>
then.call(argSource, arg => fn(arg, ...settledHistory))
);
}
}
return fn(argSource, ...history);
};
const chain = (...fns) =>
initialValue => fns.reduce(
({ previous, collectedResults }, fn) => {
const result = chainStep(fn)(previous, collectedResults);
return {
previous: result,
collectedResults: collectedResults.concat(result),
};
},
{ previous: initialValue, collectedResults: [] }
).previous;
chain(
x => Promise.resolve(x + 1),
x => Promise.resolve(x / 2),
x => Promise.resolve(x / 2),
(_, a, b, c) => [a, b, c]
)(0)
.should.eventually.deep.equal([1, 1 / 2, 1 / 4]);
// run it: https://jsfiddle.net/mnayn4L4/1/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment