I can write a simple function that uses a helper function to do work:
function calculate(a,b,fn){
return fn(a,b);
}
function sum(args){
total = 0;
for (var i=0; i<arguments.length; i++){
total += arguments[i];
}
return total;
}
console.log(calculate(15,8,sum));
As it's constructed now, the initial function will take 2 arguments and a function as its parameters. How do I configure it to accept ANY number of arguments plus a function? I tried:
function calculate(fn, args){
args = [].slice.call(arguments, 1);
return fn(args);
}
but in that scenario, invoking:
calculate(sum, 14, 5, 1, 3);
is the equivalent of invoking:
sum([14, 5, 1, 3]);
What's the proper way of accomplishing this?