const compose = (...fns) =>
fns.reduceRight((prevFn, nextFn) =>
(...args) => nextFn(prevFn(...args)),
value => value
);
Create the function, composed of three others:
const example = compose(
val => { console.log(1); return `1<${val}>`; },
val => { console.log(2); return `2<${val}>`; },
val => { console.log(3); return `3<${val}>`; }
);
Call the function:
example('hello')
Console output is:
3
2
1
"1<2<3<hello>>>"
I like the version of this at the end of this Medium post so you don't have to use an array.
I think it's also useful to provide a function similar to Ramda's
pipe
as sometimes it's more readable to go the other way, e.g.const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
const pipe = (...fns) => compose.apply(compose, fns.reverse());