Building a Compose Helper
You'll learn: How to create a reusable compose utility that chains functions together right-to-left automatically.
The Problem with Manual Composition
In the previous lesson, you saw manual composition using nested function calls like fn3(fn2(fn1(x))). This works, but it's hard to read and maintain, especially with many functions.
The Compose Helper
A compose helper takes any number of functions as arguments and returns a new function. When you call that new function with a value, it flows through all the original functions right-to-left (innermost to outermost).
Think of it like an assembly line running in reverse: the last function you pass in processes the data first.
Building It
function compose(...fns) {
return function(value) {
return fns.reduceRight((acc, fn) => fn(acc), value);
};
}
// Usage
const add5 = x => x + 5;
const double = x => x * 2;
const subtract3 = x => x - 3;
const transform = compose(subtract3, double, add5);
console.log(transform(10)); // ((10 + 5) * 2) - 3 = 27
How It Works
composeaccepts multiple functions using rest parameters- It returns a new function that accepts an initial
value reduceRightapplies each function from right-to-left, passing the result forward- The accumulator (
acc) carries the transformed value through each step
The order is add5 → double → subtract3, even though subtract3 appears first in the argument list.
Key Takeaway: A compose helper uses reduceRight to create a reusable, readable pipeline that applies functions right-to-left, eliminating nested call syntax and enabling clean functional composition.