Magicsheet logo

Function Composition

Easy
12.5%
Updated 8/1/2025

Asked by 3 Companies

Topics

Function Composition

What is this problem about?

The Function Composition interview question is a fundamental JavaScript/TypeScript task. You are given an array of functions [f1, f2, f3, ..., fn]. You need to return a new function that represents the composition of these functions. The composition of f(g(x)) means that the output of g(x) becomes the input to f(). In this problem, the functions are applied from right to left (i.e., fn is applied first, then fn-1, down to f1). If the array is empty, it should return the identity function x => x.

Why is this asked in interviews?

Companies like Meta and Google ask the Function Composition coding problem to assess a candidate's understanding of Functional Programming concepts in JavaScript. It tests your knowledge of higher-order functions, closures, and array methods. It’s a core concept used heavily in libraries like Redux (e.g., the compose function) and utility libraries like Lodash.

Algorithmic pattern used

This problem is perfectly suited for the Array.prototype.reduceRight() pattern.

  1. Return a new function that takes an initial value x.
  2. Inside the returned function, use reduceRight on the array of functions.
  3. The accumulator starts as x.
  4. In each step, apply the current function to the accumulator: acc = currentFunction(acc).
  5. Return the final accumulated value. Alternatively, a simple for loop running backwards from length - 1 down to 0 works perfectly and is often slightly faster.

Example explanation

Functions: [x => x + 1, x => x * x, x => 2 * x] Initial value: x = 4

  1. Apply the last function (x => 2 * x): 2imes4=82 imes 4 = 8.
  2. Apply the middle function (x => x * x): 8imes8=648 imes 8 = 64.
  3. Apply the first function (x => x + 1): 64+1=6564 + 1 = 65. Result: 65.

Common mistakes candidates make

  • Wrong Order: Applying the functions from left to right instead of right to left.
  • Not returning a function: Returning the evaluated result directly instead of returning a new function that can be evaluated later.
  • Empty Array handling: Forgetting to handle the edge case where the array of functions is empty, which should just return the input value unmodified.

Interview preparation tip

Be prepared to explain the difference between reduce and reduceRight. Also, knowing how to implement this using a standard for loop demonstrates that you understand the underlying mechanics of higher-order array methods.

Similar Questions