Saturday, November 20, 2010

JavaScript: varargs

The bad news is there's no simple varargs syntax in JavaScript. The good news is there are some workable patterns that can help if varargs are the right thing for your function.

arguments is an array like object, not an actual Array. It contains all the arguments passed to a function regardless of the named parameters. We're going to take that array like thing and turn it into a real Array, ignore the part that corresponds to the names arguments, then pull that array apart into variables. We'll assign some default values if we didn't get enough arguments.

function fn1(a) {
var args = Array.prototype.splice(1, arguments),
b = (args.length > 0) ? args.shift() : null,
c = (args.length > 0) ? args.pop() : {};

fn2.apply(null, [a, b].concat(args).concat([c]));
}

We use the splice method to get a real Array, and notice how we start at 1 to skip over our 1 named argument.

We use shift to take the left most of the varargs. Notice how we check if there are any arguments available and if not assign a default of null. We use pop to take arguments from the end of the list.

If there were more arguments they will be left in the args variable.

The body of this function calls another function, fn2, with the same arguments used for fn1. I'm using apply which takes an array of arguments so that I can put my variable number of left overs back in the middle.

No comments:

Post a Comment