DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 9: compose function


Write a function called compose that accepts multiple functions as arguments and returns a new function. The new function should apply the input functions in reverse order, passing the result of each function call as an argument to the next.

function double(x) {
  return x * 2;

function square(x) {
  return x * x;

function increment(x) {
  return x + 1;

const composedFunction = compose(increment, square, double);
const result = composedFunction(10); // Result: 401
Enter fullscreen mode Exit fullscreen mode

🤫 Check the comment below to see answer.

Top comments (1)

dhrn profile image
Dharan Ganesan
function compose(...functions) {
  return function (input) {
    return functions.reduceRight((acc, func) => func(acc), input);
Enter fullscreen mode Exit fullscreen mode