While recursive scans are commonly use to scan through nested objects / data. It can go on an infinite loop, if some of the objects references one another. So what is the most effective way to scan all items, without crashing the computer, nor skipping a specified parameter?
Here is an example of a recursive scanner...
/**
* Triggers the scan function for each object given
**/
function recursiveScanner( object:* , scanFunction:Function ):void {
if( typeof(object) == 'object' ) {
for( var key:String in object ) {
recursiveScanner( object[key], scanFunction );
}
} else {
scanFunction.call(this, object);
}
}
However a huge problems occur when the following is passed in
//...
obj1.next = obj2;
//...
obj2.next = obj3;
//...
obj3.next = obj1;
//...
recursiveScanner(obj1, scanFuction);
The objects will trigger scans for one another in an eternal loop. So is there a way to solve this?
I do believe in C/C++ : Each scanFunction call, will be added into a list consisting of scanned 'memory address', thus preventing a repeat. Is this even possible in AS3? Is there a more elegent way?
Use a Dictionary to keep a list of scanned objects and ignore them if they've been scanned before:
/**
* Triggers the scan function for each object given
**/
function recursiveScanner( object:* , scanFunction:Function, ignoreList:Dictonary = null ):void {
// if we have no list, create one
if (!ignoreList) ignoreList = new Dictionary();
// if the item is in the list, we bail
if (ignoreList[object]) return;
// mark the item as scanned before recursing into it
ignoreList[object] = true;
if( typeof(object) == 'object' ) {
for( var key:String in object ) {
recursiveScanner( object[key], scanFunction, ignoreList );
}
} else {
scanFunction.call(this, object);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With