I think I have the recursion working properly, but I’m not able to get the originally requested item’s property set to the right value.
The goal here is to find the topmost parent (or “ancestor,” depth = 0) of the nested item (a taxonomy based on Dictionary “parent” attributes), and assign that originally requested nested item’s “ancestor” property accordingly.
For instance, in
Apples
– Red
– – Empire
– – – Fresh
“Fresh”‘s ancestor should be set to “Apples.”
While I’m attempting this on an “on-demand” and individual basis, I’m open to a solution that tags all children that are related to the same ancestor in one fell swoop or for statement, since that would probably be more efficient.
REQUEST
for (var mc:Object in taxonomy) {
var term = taxonomy[mc];
term["ancestor"] = getAncestor(term);
trace("Setting " + term.name + "'s ancestor as [" + term.ancestor + "]");
... }
FUNCTION
function getAncestor(term:Object):String {
var ancestor = "default";
for(var obj:Object in taxonomy) {
if(term.parent == taxonomy[obj].tid) { // If next object is current object's parent
if(taxonomy[obj].depth == 0) { // And if object's parent is a root object
// Then object's parent is the ancestor
trace(term.name + "'s parent IS the root (" + taxonomy[obj].name + "). DONE."); // "term" here is NOT originally requested term
return(taxonomy[obj].name); // Return DIRECTLY to function call and assign originally requested term with this name.
break; // Get the hell out of here
}
else { // If object's parent is not a root object
trace(term.name + "'s parent (" + taxonomy[obj].name + ") is NOT a root. LOOPING.");
getAncestor(taxonomy[obj]); // Step function again with current object's parent object as current object
}
}
}
return(ancestor);
}
Finally, here is a snippet of the traced output based on my many debug statements:
treatment’s parent (Eating Disorders) is NOT a root. LOOPING.
Eating Disorders’s parent (Psychosomatic) is NOT a root. LOOPING.
Psychosomatic’s parent (Disease/Illness) is NOT a root. LOOPING.
Disease/Illness’s parent (Personal) is NOT a root. LOOPING.
Personal’s parent (Health) is NOT a root. LOOPING.
Health’s parent IS the root (People). DONE.
Setting treatment’s ancestor as [default]
As you can see, while the recursion does find the root, the originally requested item still gets the default value. What am I missing?
I’m guessing in that else statement you want:
Right now you’re calling the recursion but doing nothing with the return value, so you’re never updating the ancestor variable.
Also, that
breakafter thereturnstatement is rather pointless. 🙂If I’m understanding things correctly, you might actually be able to do:
Otherwise your loop will keep running. Without that your loop will go over everything in the taxonomy, even if the first one it sees is the one it recurses on.