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

 

senocular.com ActionScript Library

recurseWhile.as

Name: Function.prototype.recurseWhile() - (MX) runs function recursively on argument, while condition is m
Author: senocular: www.senocular.com
Date: 1899-12-31T00:23:17.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) as long as passed function remains true.
 
Arguments:
- arg: argument to be used in first call of the function.  Successive calls run
through the return value given in return.
- func: function with boolean return value which the returned value of the recursion
is tested against.  When this becomes false, the recursion is ended.
- rmax: (optional) positive integer which gives a break point for the maximum number
of loops in the recursions. If this isn't given, or is a non-positive integer, the loop
could crash the player if the recursion is never correctly ended with the passed function.


Example:
function AddTen(n){
	return n+10;
}
function isLow(n){
	return (n < 1000);
}
trace(AddTen.recurseWhile(0, isLow, 25)); // traces 250 - only added ten 25 times

1
2
3
4
5
6
7
8
9
10
Function.prototype.recurseWhile = function(arg, func, rmax){
	var r = this(arg);
	if (arguments.length == 2) var rmax = -1;
	else rmax--;
	while (rmax && func(r)){
		r = this(r);
		rmax--;
	}
	return r;
}