Write a function `compose(...fns)` that returns a function that applies the functions from right to left.
Problem Statement
Examples
Input: const add2 = x => x + 2, mult3 = x => x * 3; compose(add2, mult3)(4)
Output: 14
Explanation: mult3(4) = 12, then add2(12) = 14.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Function Composition, we consider the execution characteristics of JavaScript engines. Write a function `compose(...fns)` that returns a function that applies the functions from right to left. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.
Step-by-Step Approach
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (composition means f(g(x)). the rightmost function runs first).
- Implement Logic: Handle state and transformations efficiently (use array.reduceright() to apply functions from right to left).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function compose(...fns) {
return (x) => fns.reduceRight((acc, fn) => fn(acc), x);
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Empty or boundary inputs (empty arrays, strings, zero length).
- Type checks and unexpected values (e.g.
null,undefined, negative numbers). - Closure preservation and memory isolation between separate invocations.