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.
var compose = function(functions) {
return function(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
這題蠻燒腦的,一開始有點打結,困難點在於裡面原本寫死的 return function(x){}
不過想通後,就有種打通的感覺,但是後面一直卡在 case 1,卡了一陣子,怎麼算都是 50,不是 65 呀。
後來多學了一招 reduceRight 是從右至左的方法,就對了,如下:
var compose = function(functions) {
return function(x) {
return functions.reduce((result, fn) => fn(result), x)
};
};
改用 reduceRight
var compose = function(functions) {
return function(x) {
return functions.reduceRight((result, fn) => fn(result), x)
};
};