2

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?

kjarsenal
  • 934
  • 1
  • 12
  • 35
  • This might be of help - http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function – Jaanus Varus Jun 16 '15 at 14:00

2 Answers2

3

Using Function.apply. It lets you pass an array and it turns each member of the array as each argument to the function being called.

function calculate(fn){
    var args = [].slice.call(arguments, 1);
    return fn.apply(this, args);
}

Another example, if you have an array and you want to find out the highest number in it.

function max(array) {
    // Math.max takes separate arguments, turn each member of the array 
    // into a separate argument
    return Math.max.apply(Math, array);
}

Or using calculate:

calculate(Math.max, 3, 2, 4, 7, 23, 3, 6); // 23
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

The easiest way I can think of is wrapping the arguments in an array or an object and iterating through it inside the function.

davguij
  • 808
  • 7
  • 12