JavaScript & V8 Internals (536 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)
What are compose and pipe functions?
senior LevelCode ExamplePipesMemory ManagementDocker & Containers
The "compose" and "pipe" are two techniques commonly used in functional programming to simplify complex operations and make code more readable. They are not native to JavaScript and higher-order functions. the compose() applies right to left any number of functions to the output of the previous function.
Practical Code Example
javascript
// Compose: Evaluates right-to-left: f(g(x))
const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x);
// Pipe: Evaluates left-to-right: g(f(x))
const pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x);
const add2 = (n) => n + 2;
const multiply3 = (n) => n * 3;
console.log(compose(multiply3, add2)(5)); // (5 + 2) * 3 = 21
console.log(pipe(add2, multiply3)(5)); // (5 + 2) * 3 = 21