# 2629. Function Composition Solved Easy Given an array of functions [f1, f2, f3, ..., fn], 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 <= 1000 * 0 <= functions.length <= 1000 * all functions accept and return a single integer ## 📝 Solution 1 – reduceRight (āϏāĻŦāĻšā§‡ā§Ÿā§‡ āϏāĻ‚āĻ•ā§āώāĻŋāĻĒā§āϤ) ```js /** * @param {Function[]} functions * @return {Function} */ var compose = function(functions) { return function(x) { return functions.reduceRight((acc, fn) => fn(acc), x); }; }; ``` ## 📝 Solution 2 – for āϞ⧁āĻĒ (reverse āĻ•āϰ⧇) ```js /** * @param {Function[]} functions * @return {Function} */ var compose = function(functions) { return function(x) { let result = x; for (let i = functions.length - 1; i >= 0; i--) { result = functions[i](result); } return result; }; }; ``` ## 📝 Solution 3 – for...of + slice().reverse() ```js /** * @param {Function[]} functions * @return {Function} */ var compose = function(functions) { return function(x) { let result = x; for (const fn of functions.slice().reverse()) { result = fn(result); } return result; }; }; ``` ## 📝 Solution 4 – āϰāĻŋāĻ•āĻžāĻ°ā§āϏāĻŋāĻ­ (recursive) ```js /** * @param {Function[]} functions * @return {Function} */ var compose = function(functions) { if (functions.length === 0) return x => x; // identity return function(x) { // āĻĒā§āϰāĻĨāĻŽ āĻĢāĻžāĻ‚āĻļāύ āĻŦāĻžāĻĻ āĻĻāĻŋā§Ÿā§‡ āĻŦāĻžāĻ•āĻŋ āĻĢāĻžāĻ‚āĻļāύ⧇āϰ āĻ•āĻŽā§āĻĒā§‹āϜāĻŋāĻļāύ āĻŦāĻžāύāĻžāĻšā§āĻ›āĻŋ const [first, ...rest] = functions; const composedRest = compose(rest); return first(composedRest(x)); }; }; ``` ## ✅ āωāĻĻāĻžāĻšāϰāĻŖ ```js const functions = [x => x + 1, x => x * x, x => 2 * x]; const fn = compose(functions); console.log(fn(4)); // Output: 65 ``` ## 🚀 āĻ•āĻŋāĻ­āĻžāĻŦ⧇ āĻ•āĻžāϜ āĻ•āϰ⧇: - āφāĻŽāϰāĻž āĻāĻ•āϟāĻŋ āύāϤ⧁āύ āĻĢāĻžāĻ‚āĻļāύ āϰāĻŋāϟāĻžāĻ°ā§āύ āĻ•āϰāĻŋ āϝāĻž āχāύāĻĒ⧁āϟ x āĻ¨ā§‡ā§ŸāĨ¤ - reduceRight āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻ•āϰ⧇ āĻĒā§āϰāϤāĻŋāϟāĻŋ āĻĢāĻžāĻ‚āĻļāύāϕ⧇ āĻĄāĻžāύ āĻĻāĻŋāĻ• āĻĨ⧇āϕ⧇ āĻŦāĻžāρ āĻĻāĻŋāϕ⧇ āĻĒā§āĻ°ā§Ÿā§‹āĻ— āĻ•āϰāĻŋāĨ¤ - āĻĒā§āϰāϤāĻŋāϟāĻŋ āĻĢāĻžāĻ‚āĻļāύ⧇āϰ āφāωāϟāĻĒ⧁āϟ āĻĒāϰ⧇āϰ āĻĢāĻžāĻ‚āĻļāύ⧇āϰ āχāύāĻĒ⧁āϟ āĻšā§ŸāĨ¤