// ⭐ pipe:
// - pipe(f1, f2, f3 ...)(x,y,z ...) = ...f3(f2(f1(x,y,z ...)))
// ╰── funcs ───╯ ╰──args──╯
function pipe(...funcs) {
return function(...args) {
return funcs.slice(1).reduce(
(result, f) => f.call(this, result), // r = ...f3(f2(r))
funcs[0].apply(this, args) // r = f1(x,y,z ...)
);
};
}
// ⭐ compose:
// - compose(f, g, h)(x) = f(g(h(x))) = pipe(h, g, f)(x)
function compose(...funcs) {
return pipe(...funcs.slice().reverse());
}
const sum = (x, y) => x + y;
const square = x => x * x;
const add3 = x => x + 3;
compose(square, sum)(2, 3) // 25
pipe(sum, square)(2, 3) // 25
pipe(sum, square, add3)(2, 3) // 28