Function Composition | #2629 | LeetCode Solution

Author: neptune | 09th-Sep-2023
#JavaScript #LeetCode

Problem : Function Composition | #2629 | LeetCode

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


Solution:

         /**

     * @param {Function[]} functions

     * @return {Function}

     */

    var compose = function (functions) {

        return function (x) {

            if (functions.length === 0) {

                return x;

            } else {

                let result = x;

                for (let i = functions.length - 1; i >= 0; i--) {

                    result = functions[i](result);

                }

                return result;

            }

        }

    };


    /**

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

     * fn(4) // 9

     */


Explanation:

Let's break down the code step by step:


1. The code defines a function called `compose` which takes one parameter, `functions`. It's intended to create a new function by composing an array of functions together.


2. Inside the `compose` function, a new function is returned. This returned function takes one parameter, `x`, which is the input value to be processed by the composed functions.


3. The function checks if the `functions` array is empty by examining its length using `functions.length === 0`. If it's empty, it simply returns the input value `x` because there are no functions to apply.


4. If the `functions` array is not empty, the code initialises a variable `result` with the value of `x`. This variable will be used to accumulate the result of applying the composite functions.


5. It then enters a `for` loop that iterates through the `functions` array in reverse order, starting from the last function in the array and moving towards the first.


6. Inside the loop, each function in the `functions` array is applied to the `result`, and the updated value is stored back in the `result` variable. This effectively composes the functions in reverse order, with the last function being applied first.


7. After the loop has processed all the functions, the final `result` value represents the output of applying the composite functions to the input `x`.


8. The final `result` value is returned as the result of the function created by `compose`.


In summary, the `compose` function takes an array of functions and returns a new function that applies these functions to an input value `x`, composing them in reverse order. This allows you to create a single function that combines multiple functions to process input data. In the example provided, `compose` is used to create a new function `fn` that applies two functions: `x => x + 1` and `x => 2 * x`, resulting in the output `9` when `fn(4)` is called.





Related Blogs
Managing Virtual Environments in React JavaScript Projects
Author: neptune | 28th-Jun-2023
#JavaScript #React.js
Virtual environments are a valuable tool in React JavaScript projects as they allow developers to isolate dependencies, manage package versions, and maintain project consistency...

A Guide to Writing Clean, Readable, and Maintainable Code in JavaScript
Author: neptune | 23rd-Feb-2024
#JavaScript
By incorporating these principles into your coding practices, you contribute to creating code that is not only functional but also maintainable and easily understandable by your peers...

From REST to GraphQL: The Future of API Design
Author: neptune | 25th-Feb-2024
#JavaScript
Unlike traditional REST APIs, GraphQL provides a more flexible and intuitive approach to data querying and retrieval...

How I Built My Blogging Website Using React, Node.js, and Jamstack Architecture?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Building a blogging website using React, Node.js, and Jamstack architecture was a rewarding experience...

Why, What, and When: Understanding Jamstack?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Jamstack represents a modern approach to web development that addresses many of the challenges faced by traditional architectures...

How to Get Started with Jamstack: A Comprehensive Guide?
Author: neptune | 05th-Jul-2024
#JavaScript #API
Getting started with Jamstack involves choosing the right tools, setting up a structured development environment...

How to Perform Unit Testing in React Components with Examples?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
Unit testing in React is an essential practice to ensure the reliability and robustness of your components...

Do you know ! How to manage State in Functional & Class Components in React ?
Author: neptune | 25th-Jul-2024
#JavaScript #React.js
State management in React has evolved significantly with the introduction of Hooks...

View More