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.
接受一個函數陣列[f1, f2, f3, ..., fn]
作為參數,返回一個新函數fn
,它是函數陣列的函數組合。[f(x), g(x), h(x)]
的函數組成為 fn(x) = f(g(h(x)))
。
空函數列表的函數組合是恆等函數 f(x) = x
。
您可以假設數組中的每個函數接受一個整數作為輸入並返回一個整數作為輸出。
compose
作為組合陣列的方法,而它的參數則為函式陣列functions
function compose(functions) {
if (functions.length === 0) {
return (x) => x;
}
//調用函式陣列的邏輯
}
for(初始,判斷,迭代)
),陣列最後一個元素開始遍歷到第一項元素,由於希望從陣列最後一項Array[index]
開始,陣列中末項元素的索引index
用Array.lenth-1
求出。function compose(functions) {
if (functions.length === 0) {
return (x) => x;
}
return function (x) {
let result = x;
for (let i = functions.length - 1; i >= 0; i--) {
result = functions[i](result);
}
return result;
};
}
currentFunction
後,返還result
作為下一次函式的參數。function compose(functions) {
return function (x) {
return functions.reduceRight((result, currentFunction) => {
return currentFunction(result);
}, x);
};
}
let functionsX = [x => x + 1, x => x * x, x => 2 * x];
let x = 4;
const composedFunction = compose(functionsX);
const result = composedFunction(x);
console.log(result);
let functionsY = [y => 10 * y, y => 10 * y, y => 10 * y];
let y = 1;
const composedFunctionY = compose(functionsY);
const resultY = composedFunctionY(y);
console.log(resultY);
let functionsZ = [];
let z = 42;
const composedFunctionZ = compose(functionsZ);
const resultZ = composedFunctionZ(z);
console.log(resultZ);