Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Composing several functions using a compose utility

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading