Implement compose and pipe
Write two helpers for function composition:
pipe(...fns)returns a function that runsfnsleft to right, passing each result to the next functioncompose(...fns)does the same right to left, socompose(f, g)(x)isf(g(x))
The first function to run may receive any number of arguments; every later one receives the single previous result. With no functions, both return a function that gives back its first argument unchanged.
pipe((x) => x + 1, (x) => x * 2)(3)→8compose((x) => x + 1, (x) => x * 2)(3)→7pipe((a, b) => a + b, (x) => x * 10)(2, 3)→50compose()(5)→5
Define compose, pipe in the editor. 7 tests will call them.
Hint 1pipe is a reduce over the functions, where the accumulator is the value so far.
Hint 2Call the first function with all the arguments yourself, then reduce over the rest, passing each the previous result.
Hint 3compose is pipe with the functions reversed. Copy before reversing (or use reduceRight) so you don't mutate the list, and do the work once up front rather than on every call.
one clean solution
function pipe(...fns) {
return function (...args) {
if (fns.length === 0) return args[0];
const [first, ...rest] = fns;
return rest.reduce((value, fn) => fn(value), first(...args));
};
}
function compose(...fns) {
return pipe(...[...fns].reverse());
}