# 2629. Function Composition ###### tags:`Function` | `leetCode` <font color="#01AE9A" background="E1F3F0">`easy`</font> ### 題目 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 ```javascript= 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 ``` ```javascript= 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 ``` --- ### 解題邏輯 這題要注意看他提示的呼叫 fn 的方式 ```javascript= /** * const fn = compose([x => x + 1, x => 2 * x]) * fn(4) // 9 */ ``` 因為我一開始一直不知道這個4是怎麼傳進去的,還自己亂加第二個參數XD ```javascript= var compose = function(functions) { return function(x) { if(functions.length===0)return x for(let i = functions.length-1;i>=0;i--){ x =functions[i](x) } return x } }; const fn = compose([x => x + 1, x => 2 * x]) fn(4) // 9 ``` 4會在return fun 裡面接到,然後再將迴圈的初始條件設成 functions 的最後一個就可以了 --- 在解析中還有看到 reduceRight 的寫法蠻酷的給大家參考 ```javascript= function compose(functions): F { return (x: number) => functions.reduceRight((acc, f) => f(acc), x); } ; ```