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?

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.