Composing several functions using a compose utility

Advertisements

I am supposed to create a function that takes some functions as arguments, and returns a composition of those arguments in the following way:
Given functions fnN, fn(N-1), …, fn1, and a value v, the function should return the result of

compose(fnN, fnN-1, ..., fn1)(v) = fnN(fnN-1(...(fn1(v))));

I would be grateful if someone can help out and answer why this method doesn’t:

function compose(...fns) { 
  return function composed(v) {
    if (fns.length >= 2) {
      return fns[0](compose(...fns.slice(1)));
    } else return fns[0](v);
  }
}

Thank you!

I know that this solution works for example:

function compose(...fns) {
  return function(v) {
    for (let fn of fns) {
      v = fn(v);
    }
    return v;
  }
}

>Solution :

You need to fix you recursive call to call the resulting function with a given argument.

function compose(...fns) { 
  return function composed(v) {
    const [first, ...rest] = fns;
    if (!rest.length) return first(v)
    
    return first(compose(...rest)(v))
  }
}


function inc(x) { return x + 1 }


console.log(compose(inc, inc, inc)(0))

Leave a Reply Cancel reply