Search code examples
javascriptfunctionvariadic

How to create a variadic high-order function reusing the returned result in JS


Consider I have an undetermined number of functions f, each one needing one argument and returning one result. How should I write a function "execute" taking the first argument as the number, and all the other arguments as functions to be applied to the result of each preceding function?

Here's my guess:

let plus1 = d => d += 1;
let plus2 = d => d += 2;
let write = d => document.write(d);


let execute = function(n,...functions){
  functions.forEach((d)=>d(n));
}

execute(4,plus1,plus2,write); 

I'm expecting 7 ((4+1)+2).

Thanks for your help!


Solution

  • You could use Array#reduce, which returns a result, while using a function with a given value.

    let plus1 = d => d + 1,
        plus2 = d => d + 2,
        write = d => console.log(d),
        execute = (n, ...fn) => fn.reduce((n, f) => f(n), n);
    
    execute(4, plus1, plus2, write); 

    Shorter version as Yury Tarabanko suggested

    let plus1 = d => d + 1,
        plus2 = d => d + 2,
        write = d => console.log(d),
        execute = (...args) => args.reduce((v, f) => f(v));
    
    execute(4, plus1, plus2, write);