Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

recurse.as

Name: Function.prototype.recurse() - (MX) runs function recursively on argument, n times
Author: senocular: www.senocular.com
Date: 1899-12-31T00:54:51.700
Documentation:
Function RECURSE (MX): recurses a function to call
itself a certain number of times on its own return value (if
there is one).
 
Arguments:
- arg: argument to be used in first call of the function.  Successive calls run
through the return value given in return.
- n: number of times to call the function on itself.  If this number is 1 or less
the function is run once and the return value (if exists) is returned.

Example:
function Double(n){
	return n+n;
}
// Double recursing 2, 4 times:
trace(Double.recurse(2,4)); // trace 32 which is 2+2=4+4=8+8=16+16=32

1
2
3
4
5
6
Function.prototype.recurse = function(arg, n){
	var i, r = this(arg);
	if (n < 2) return r;
	for (i=1;i<n;i++) r = this(r);
	return r;
}