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.
給予一個陣列函式 [f1, f2, f3, ..., fn],回傳一個新的函式 fn 是這個陣列函式的函式組合。 函式組合[f(x), g(x), h(x)]為fn(x) = f(g(h(x)))。 假如為空的函式列表的函式組合,則函式恆為input的值,如f(x) = x。 你可以假設陣列中的每個函式都接受一個整數作為輸入,並回傳一個整數當作結果。
Example 1:
Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4 Output: 65
Example 2:
Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1 Output: 1000
Example 3:
Input: functions = [], x = 42 Output: 42
solution:
這題最重要的是了解題目的說明,題目將條件依序放到陣列中,
同時希望我們由右到左的讀取陣列函式的內容,
這個過程我們可以使用reduceRight()來完成指定功能,如下:
Code 1: BigO(n)
var compose = function(functions) { return function (x) { return functions.reduceRight((acc, cur) => cur(acc), x); }; };
FlowChart:
Example 1
Input: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4 functions.reduceRight((acc, cur) => cur(acc), x) functions.reduceRight((acc, cur) => cur(2 * 4), 4) //acc = 8 functions.reduceRight((acc, cur) => cur(8 * 8), 8) //acc = 64 functions.reduceRight((acc, cur) => cur(64 + 1), 64) //acc = 65 return 65;
Example 2
Input: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1 functions.reduceRight((acc, cur) => cur(acc), x) functions.reduceRight((acc, cur) => cur(10 * 1), 1) //acc = 10 functions.reduceRight((acc, cur) => cur(10 * 10), 10) //acc = 100 functions.reduceRight((acc, cur) => cur(10 + 100), 100) //acc = 1000 return 1000;
Example 3
Input: functions = [], x = 42 functions.reduceRight((acc, cur) => cur(acc), x) functions.reduceRight((acc, cur) => cur(acc), 42) return 42;
Code 2: BigO(n)
var compose = function(functions) { return function (x) { return functions.reverse().reduce((acc, cur) => cur(acc), x); }; };
Code 3: BigO(n)
var compose = function(functions) { return function(x) { while (functions.length) { x = functions.pop()(x); } return x; } };
Code 4: BigO(n)
var compose = function(functions) { return function recursion(x) { //如果funcitons中沒有陣列元素,則呼叫temp匿名函式回傳x的值。 if (functions.length === 0) return x; //*重點,將x重新賦值為:移除functions中最右邊的陣列的同時,帶入(x)的參數進去執行取得結果。 x = functions.pop()(x); //重複呼叫遞迴函式直到陣列中無元素。 return recursion(x); } };