Antonio Ortiz Antonio Ortiz - 2 months ago 11
Javascript Question

How do you apply an arbitrary numbers of arguments passed to function which is argument of another function in JavaScript?

How would you apply a unlimited number of arguments to a function which is a parameter of another function?

This is what I tried:

var callIt = function(fn) {
for(var i = 1; arguments.length + 1; i++){
return fn(arguments[i]);
}
};


There is a function in the exercise which is used to convey what is being asked:

callIt(sumAll, 1);


Maybe I've had too many beers...

callIt(sumAll, 2,3) // 5 is expected but I got 2

Answer

Make the argument an array, remove the first element, use apply.

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

Or working from your code:

var callIt = function(fn) {
    var args = [];
    for(var i = 1; i < arguments.length; i++){
        args.push(arguments[i]);
    }
    return fn.apply(null, args);
};