Member-only story
Javascript Interview: Function Composition: pipe()

What is function composition ?
In JavaScript, function composition is the practice of combining two or more functions to create a new function. The idea is similar to mathematical function composition: you apply one function to the result of another.
For example, if you have two functions
f
andg
, the composition off
andg
, written asf(g(x))
, means that the result ofg(x)
is passed as an argument tof
.
// Two simple functions
const add2 = (x) => x + 2;
const multiplyBy3 = (x) => x * 3;
// Function composition
const compose = (f, g) => (x) => f(g(x));
// Compose add2 and multiplyBy3
const add2ThenMultiplyBy3 = compose(multiplyBy3, add2);
console.log(add2ThenMultiplyBy3(5)); // Result: 21
Interview Question
You are asked to create a pipe()
function, which chains multiple functions together to create a new function.
Suppose we have some simple functions like this
const times = (y) => (x) => x * y
const plus = (y) => (x) => x + y
const subtract = (y) => (x) => x - y
const divide = (y) => (x) => x / y
You have to create a pipe
function in JavaScript that takes an array of functions and returns a new function. This new function, when called with an initial value, will apply each of the functions in the array to the value in order, from left to right.
When the pipe
function is called with the array:
pipe([
times(2),
times(3)
])
It should return a function that, when invoked with an argument (say x = 5
), applies the times(2)
function first, then the times(3)
function, and returns the result:
- First,
times(2)(5)
is5 * 2 = 10
- Then,
times(3)(10)
is10 * 3 = 30
So, calling the result with5
will return30
Solution
Lets break down the problem —
- The
pipe
function should take an array of functions. - Each function in the array should be applied to the result of the previous function.
- The order of functions in the array matters (left to right).