Practical ReduceRight: Composing Functions
You'll learn how to use reduceRight to compose functions so they execute right-to-left, just like mathematical composition.
The Core Idea
In mathematics, when you compose functions like (f ∘ g)(x), you apply g first, then f to the result. That's right-to-left execution. reduceRight naturally supports this pattern by processing an array of functions from right to left, building a single composed function.
Think of it like wrapping gifts: the innermost wrapper (rightmost function) goes on first, then each subsequent wrapper builds outward.
How It Works
When you have multiple transformation functions, reduceRight creates a pipeline where:
- The rightmost function executes first on the input
- Each function to the left receives the previous function's result
- You end up with one function that chains all transformations
const add5 = x => x + 5;
const multiplyBy2 = x => x * 2;
const subtract3 = x => x - 3;
const functions = [subtract3, multiplyBy2, add5];
// Compose right-to-left: subtract3(multiplyBy2(add5(x)))
const composed = functions.reduceRight((accumulatedFn, currentFn) => {
return value => accumulatedFn(currentFn(value));
});
console.log(composed(10));
// add5(10) = 15
// multiplyBy2(15) = 30
// subtract3(30) = 27
The accumulator holds the growing chain of composed functions, and each iteration wraps it with the next function from right to left.
Why Right-to-Left?
This matches mathematical notation and makes the execution order match the visual order in your array when thinking "apply these transformations in sequence."
Key Takeaway: Use reduceRight to compose functions right-to-left, creating a single function that applies transformations in the order they appear mathematically, with the rightmost function executing first.