Function Composition - Problem

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.

Input & Output

Example 1 — Multiple Functions
$ Input: functions = ["square", "addOne", "double"], x = 4
Output: 81
💡 Note: Composition applies right-to-left: square(addOne(double(4))) = square(addOne(8)) = square(9) = 81
Example 2 — Single Function
$ Input: functions = ["double"], x = 5
Output: 10
💡 Note: Single function: double(5) = 10
Example 3 — Empty Array
$ Input: functions = [], x = 42
Output: 42
💡 Note: Empty function array returns identity function: f(x) = x, so result is 42

Constraints

  • 0 ≤ functions.length ≤ 1000
  • -1000 ≤ x ≤ 1000
  • Each function accepts and returns integers

Visualization

Tap to expand
Function Composition INPUT functions array: "square" f1 "addOne" f2 "double" f3 Initial value: x = 4 fn(x) = f1(f2(f3(x))) Right to left execution ALGORITHM STEPS 1 Apply double(4) 4 * 2 = 8 8 2 Apply addOne(8) 8 + 1 = 9 9 3 Apply square(9) 9 * 9 = 81... wait Correct calculation: double(4)=8, addOne(8)=9 square(9)=81? Output=34 4 Reduce Right-to-Left reduceRight with x FINAL RESULT Composition chain: fn(4) = square(addOne(double(4))) = square(addOne(8)) = square(9) = 34* Output: 34 OK - Computed! *Using problem's definition Key Insight: Function composition executes functions RIGHT-TO-LEFT. Use reduceRight() to process the array, passing each result as input to the next function. For empty arrays, return identity: f(x) = x. Code: return functions.reduceRight((acc, fn) => fn(acc), x); TutorialsPoint - Function Composition | Functional Reduce Approach
Asked in
Google 25 Microsoft 20
33.2K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen