게으른개발너D

[Function, Closure] Function Composition (feat. reduceRight) 본문

알고리즘/과제

[Function, Closure] Function Composition (feat. reduceRight)

lazyhysong 2023. 7. 3. 18:27

https://leetcode.com/problems/function-composition/

 

Function Composition - LeetCode

Can you solve this real interview question? Function Composition - 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(

leetcode.com

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 1:

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

Example 2:

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

Example 3:

Input: functions = [], x = 42
Output: 42
Explanation:
The composition of zero functions is the identity function

Constraints:

  • -1000 <= x <= 1000
  • 0 <= functions.length <= 1000
  • all functions accept and return a single integer

 

solution

/**
 * @param {Function[]} functions
 * @return {Function}
 */
var compose = function(functions) {
    return function(x) {
        let value = x;
        for(let i = functions.length - 1; i >= 0; i--) {
            const fn = functions[i];
            value = fn(value);
        }
        return value;
    }
};

/**
 * const fn = compose([x => x + 1, x => 2 * x])
 * fn(4) // 9
 */

solution2

/**
 * @param {Function[]} functions
 * @return {Function}
 */
var compose = function(functions) {
   if (functions.length === 0) {
      return function(x) { return x; };
   }

   return functions.reduceRight(function(prevFn, nextFn) {
      return function(x) {
         return nextFn(prevFn(x));
      };
   });

};

 

 

typescript

type F = (x: number) => number;

function compose(functions: F[]): F {
	return function(x) {
       let result = x;
       for(let i = 0; i < functions.length; i++) {
            const fn = functions[functions.length - 1 - i];
            result = fn(result);
       }
       return result; 
    }
};

/**
 * const fn = compose([x => x + 1, x => 2 * x])
 * fn(4) // 9
 */

reduceRight

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight

 

Array.prototype.reduceRight() - JavaScript | MDN

reduceRight() 메서드는 누적기에 대해 함수를 적용하고 배열의 각 값 (오른쪽에서 왼쪽으로)은 값을 단일 값으로 줄여야합니다.

developer.mozilla.org

reduceRight() 메서드는 누적기에 대해 함수를 적용하고 배열의 각 값 (오른쪽에서 왼쪽으로)은 값을 단일 값으로 줄여야한다.

적용되는 배열 순서가 reduce와 반대 방향!

const array1 = [[0, 1], [2, 3], [4, 5]];

const result = array1.reduceRight((accumulator, currentValue) => 
   accumulator.concat(currentValue)
);

console.log(result);
// Expected output: Array [4, 5, 2, 3, 0, 1]

 

Comments