Function Composition Problem
Description
LeetCode Problem 2629.
Given an array of functions [f1, f_2, f_3, ..., f_n], return a new function fn that is the function composition of the array of functions.
The function composition of [f(x), g(x), h(x)] is fn(x) = f(g(h(x))).
The function composition of an empty list of functions is the identity function f(x) = x.
You may assume each function in the array accepts one integer as input and returns one integer as output.
Example 1:
Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4
Output: 65
Explanation:
Evaluating from right to left ...
Starting with x = 4.
2 * (4) = 8
(8) * (8) = 64
(64) + 1 = 65
Example 2:
Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1
Output: 1000
Explanation:
Evaluating from right to left ...
10 * (1) = 10
10 * (10) = 100
10 * (100) = 1000
Example 3:
Input: functions = [], x = 42
Output: 42
Explanation:
The composition of zero functions is the identity function
Constraints:
-1000 <= x <= 10000 <= functions.length <= 1000- all functions accept and return a single integer
Solution
Approach: Apply from right to left
compose([f, g, h])(x) is f(g(h(x))), so the function at the end of the array runs first. Walk the array from the last element to the first, feeding each result into the next function. With reduceRight this is one line: the accumulator starts as x.
For an empty array there is nothing to apply and the accumulator stays x, which is the identity function required by the statement.
Complexity: O(k) per call for k functions, O(1) extra space.
/**
* @param {Function[]} functions
* @return {Function}
*/
var compose = function (functions) {
return function (x) {
return functions.reduceRight((acc, fn) => fn(acc), x);
};
};
/**
* const fn = compose([x => x + 1, x => 2 * x])
* fn(4) // 9
*/