Function composition is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.
Example:
const square = x => x*x;
const addTen = x => x + 10;
const result = compose(square, addTen)(20);
result: 410;
Lets write the compose function for the above question..
function compose(f1, f2){
return function(value){
return f2(f1(value));
}
}
const result = compose(square, addTen)(20);
if we console log the result, the answer would be 410.
However, the solution above is only valid if compose accepts no more than two functions. So, to make it work for an n-number of functions, we need to make a few changes.
function compose(...args){
return function(value){
return args.reduce((pre, current) => current(pre), value);
}
}
const result = compose(square, addTen, addTen, addTen)(20);
answer: 430.
// here were are using rest operator ...args to accept n-number of arguments in an array.
args.reduce() will iterate over each element/function with the previously computed value, returning the final computed value.
The function above can be shortened as below:
const compose =(...args) => value => args.reduce((pre, current) => current(pre), value);
const result = compose(square, addTen, addTen, addTen)(20);
answer: 430.
I hope this helps you solve such a problem during your interview.
Thats all for now. Keep learning and have faith in Javascript❤️
Top comments (0)