It’s an strategy the place results of one perform handed on to subsequent perform.
const add = (x, y) => x+y;
const subtract = (x) => x-4;
const multiply = (x) => x * 8;
// results of `add` is handed to `subtract` and its end result handed to `multiply`.
const end result = multiply(subtract(add(2, 3)));
end result;
> 8
That appears readable however what if we now have extra capabilities to name one after different.
Let’s attempt little cleaner strategy.
const compose = (...capabilities) => x => capabilities.reduceRight((complete, f) => f(complete), x);
const add = x => x+2;
const subtract = x => x-1;
const multiply = x => x * 8;
compose(multiply, subtract, add)(2);
> 24
We are able to additionally use scale back to implement:
const pipe = (...capabilities) => x => capabilities.scale back((complete, f) => f(complete), x);
const add = x => x+2;
const subtract = x => x-1;
const multiply = x => x * 8;
pipe(add, subtract, multiply)(2);
> 24
pipe
– performs from left-to-right.
compose
– performs from right-to-left.