Tags

Interviewed candidates for senior full-stack developer position. Here was one of my questions in the JavaScript area.

Write a function ‘compose’ that takes two unary functions and returns a unary function that calls them both.

function double(x) { return 2 * x; }

function square(x) { return x * x; }

function triple(x) { return x * x * x; }

The ‘double’, ‘square’, and ‘triple’ are unary functions. Please finish the ‘compose’ function below.

function compose(f1, f2) {

    // implement code here….

}

 

Sample outputs of invocation of function ‘compose’:

compose(double, square)(3);              // result: 36

compose(square, triple)(3);              // result: 729

 

This question tests the knowledge of function as first-class citizen, which can be passed around just like data. The question is good for interview purpose because the answer is short and simple.

The answer is at the bottom of this page.

 

 

 

 

 

 

 

function compose(f1, f2) {
     return function(x) { return f2(f1(x)); };
}

 

Advertisements