Member-only story

Javascript Interview: Function Composition: pipe()

Eishta Mittal
3 min readJust now

--

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 and g, the composition of f and g, written as f(g(x)), means that the result of g(x) is passed as an argument to f.

// 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…

--

--

Eishta Mittal
Eishta Mittal

Written by Eishta Mittal

Software Engineer passionate about Frontend Engineering

No responses yet