TobilobaCodes – LeetCode Explorer

2629. Function Composition

In this page, we will discuss LeetCode Problem 2629: Function Composition. This problem asks you to return a composed function given an array of single-argument functions.

📄 Problem Statement

Given an array of functions [f1, f2, f3, ..., fn], return a new function fn that is the composition of those functions.

The composition of functions means: fn(x) = f1(f2(f3(...(x)))). If the list is empty, return the identity function f(x) = x.

💡 Example

Input:
const fn = compose([x => x + 1, x => 2 * x]);
fn(4);
Output:
9

🧠 Explanation

The compose function should apply the given functions from right to left. You can use Array.prototype.reduceRight() to handle this cleanly. If the input array is empty, just return a function that returns its argument unchanged.

This tests your understanding of higher-order functions and functional programming.

✅ Your Solution


/**
 * @param {Function[]} functions
 * @return {Function}
 */
var compose = function(functions) {
    return function(x) {
        return functions.reduceRight((acc, fn) => fn(acc), x);
    };
};