How To Use The ...Rest Operator With Recursion in ActionScript | AS 3

How to pass an undefined number of parameters or multiple parameters into a function recursively.

The rest operator means that multiple parameters or an undefined number of parameters can be passed into a function. The rest operator is denoted by three dots (...) in the function declaration. This is what tells ActionScript that we don't know how many parameters are going to come through and thus the "args" variable is automatically created when the function is called. The "args" variable is an array of what parameters where passed into the function.

Do something like this:

ActionScript Code:

function recurseRest(i:int,...args){
if (i < args.length){
i++;
recurseRest(i,args);
trace(args[i]);
}
return;
}


recurseRest(-1,"a","b","c","d","e");



However as we all know "args" comes out as an array on the first level of recursion and when it gets passed to the second level of recursion it comes through as an array of length 1 which contains the full previous array on the first level of recursion of ["a","b","c","d","e"]. Another simple example of where using recursion would be of use:

ActionScript Code:


function externalInterfaceWrapper(funcName:String, ...args){
ExternalInterface.call("someJavascriptFunc",args);
}



This will not work! You could do something like this that will only support the number of arguments you hard code it for:

ActionScript Code:


function externalInterfaceWrapper(funcName:String, ...args){
if (args.length > 3){
trace("function aborted - expecting a max of 4, got "+(args.length+1));
return;
}

switch (args.length) {
case 0: ExternalInterface.call(callBack_str);
return;
case 1: ExternalInterface.call(callBack_str,args[0]);
return;
case 2: ExternalInterface.call(callBack_str,args[0],args[1]);
return;
case 3: ExternalInterface.call(callBack_str,args[0],args[1],args[2]);
return;
}
}



This is, of course, baaaad!!

Do this instead:


ActionScript Code:


function recurseRest(i:int,...args){
if (i < args.length){
i++;
recurseRest.apply(this,[i].concat(args));
trace(args[i]);
}
return;
}

recurseRest(-1,"a","b","c","d","e");


What is happening? [i].concat(args) is creating a new array, first element is the value of the variable 'i' and then adding the passed ...(rest) parameters. It needs ''this'' to be passed to it. That so that the function knows its scope.

Or you can use apply with the ExternalInterface like this:

ActionScript Code:


var callBack:Function = ExternalInterface.call;
try{
callBack.apply(this,[callBack_str].concat(args));
} catch (e:*){
trace("Can''t call "+callBack_str+" no external interface available");
}



BTW If you want to know whether you can call ExternalInterface methods you may use ExternalInterface.available.

comments powered by Disqus