Saturday, September 29, 2007

using arguments vs. an array parameter

This goes for both actionscript and javascript and I guess any language that lets you create functions without an arbitrary number of parameters (a syntax known as elipsis in some other languages).

It is very temping to use this syntax to write general functions such as Max or Min with an arbitrary number of parameters.

you would get something like (and this just an outline not code designed to work).

function maxOfN() {
var m=arguments[0];
for (var i=1;i if (arguments[i]>m) m=arguments[i];
return m;

you can then use this in a clean way:
var m1=maxOfN(4,8,3,9);

So what is the alternative?
Work on an explicit array of values

function maxOfN(arrValues) {
var m=arrValues[0];
for (var i=1;i if (arrValues[i]>m) m=arrValues[i];
return m;

and you get the less clean syntax:
var m1=maxOfN([4,8,3,9]);

so it looks as if its more "cool" to use the first option
but as I found out after writing some "cool" code there is a minor problem with this approach:

suppose you already have an array with the values you want to work on (as I did),
you will then have to use:

// values is set to an array of values by previous code
mar m1=maxOfN.apply(null,values);

0) Assumes you even have an apply in your language
1) Looks much worse then
var m1=maxOfN(values);
2) Actually means that you build an arry in your code, then call apply which takes the array appart, pushes it onto the stack just so that you can as for the arguments array and have all the parameters pushed back into the array you could have passed directly to begin with.

So my recomandation would be to pass the array explicitly and pay for the creation of the array parameter

var m1=maxOfN([4,8,3,9]);

This also has the advantage of being able to pass along more then a single array to a function and not being limited to having it as the last parameter of the function.

consider somthing like:
var sums=inPairs([1,3,5],add,[4,6,8]);
var products=inPairs([1,3,5],mult,[4,6,8]);

Anyone wants to guess what I would expect sums and products to be ?
Did i hear any one say "Excel" or "Array functions" ...

No comments:

Clicky Web Analytics