There are two types of function composition:
- Left-to-right function composition also known as pipe
- Right-to-left function composition also known as compose
Here is a fun recursive approach to implementation:
This assumes there are at least two functions to combine
const compose = (...fn) => {
const [[f, g], x] = [fn.slice(-2), fn.slice(0, -2)];
const h = a => f(g(a));
return x.length ? compose(...x, h) : h;
}
const pipe = (...fn) => {
const [f, g, ...x] = fn;
const h = a => g(f(a));
return x.length ? pipe(h, ...x) : h;
}
Let's test it out:
const foo = x => x + 'foo';
const bar = x => x + 'bar';
const baz = x => x + 'baz';
pipe(foo, bar, baz)('');
//=> 'foobarbaz'
compose(foo, bar, baz)('');
//=> 'bazbarfoo'