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…