문제

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.

 

예제

functions 배열에서 역순으로 함수들에 x을 넣어 나온 값을 x로 갱신시킨다.

 

마찬가지로 역순으로 함수들에 x를 삽입 후 나온 값으로 갱신시킨다.

 

functions 배열이 비어있을 경우, 정답은 항상 x이다.

 

 

코드

/**
 * @param {Function[]} functions
 * @return {Function}
 */
var compose = function(functions) {
    return function(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
 */

함수들이 들어있는 functions 배열을 역순으로 순회하며 x값을 넣은 후 반환된 값으로 x를 업데이트한다.

모든 함수를 순회하게 되면 문제에서 요구하는 값을 계산할 수 있다.

+ Recent posts