[Easy] LeetCode JS 30 - 2629. Function Composition

March 3, 2024

☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee

LeetCode 30 Days of JavaScript

This question is from LeetCode's 30 Days of JavaScript Challenge

2629. Function Composition

Question Prompt

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

Solutions

We can start by define a compose function that takes a list of functions as input and returns a new function. The new function applies the functions in the list from right to left to an argument.

This inner function is the composed function that gets returned. It expects an argument x, which will be the initial input for the composition.

Then, we initialize a variable result to the input value x. This result variable will hold the intermediate output after each function in the composition is applied. This loop iterates through the functions array in reverse order. This is crucial because function composition follows a right-to-left evaluation order.

Inside the loop, we call the current function functions[i] with the current value of result. The output of this function call becomes the new value of result. This applies each function layer-by-layer to the initial input.

After the loop completes, the final result holds the output of the entire function composition. This value is returned from the composed function.

var compose = function (functions) {
  return function (x) {
    // Start with the initial input 'x'
    let result = x;

    // Iterate through the functions in reverse order
    for (let i = functions.length - 1; i >= 0; i--) {
      // Apply each function to the current result
      result = functions[i](result);
    }

    // Return the final result
    return result;
  };
};
☕️ Support Us
Your support will help us to continue to provide quality content.👉 Buy Me a Coffee