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.
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.
This problem is perfectly suited for the Array.prototype.reduceRight() pattern.
x.reduceRight on the array of functions.x.acc = currentFunction(acc).for loop running backwards from length - 1 down to 0 works perfectly and is often slightly faster.Functions: [x => x + 1, x => x * x, x => 2 * x]
Initial value: x = 4
x => 2 * x): .x => x * x): .x => x + 1): .
Result: 65.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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Buy Two Chocolates | Easy | Solve | |
| Count Items Matching a Rule | Easy | Solve | |
| Display the First Three Rows | Easy | Solve | |
| Find Most Frequent Vowel and Consonant | Easy | Solve | |
| Increasing Order Search Tree | Easy | Solve |