This is kind of a theoretical question. I'm hoping for general advice on techniques here.

I am building a Javascript class to build a tree structure. It has a recursive method that lets you specify the structure of the tree called renderChildren. You call renderChildren with an argument, aChildren -- an array of objects representing nodes of the tree. It also takes another arg called oParent -- which is the parentNode of the children being passed. something vaguely like this:

myTree.prototype.aNodes = array();
myTree.prototype.renderChildren = function (aChildren, oParent) {

  for(var i=0; i<aChildren.length; i++) { // parse all those kids

var aChild = aChildren[i]; // take one child
var nodeID = this.aNodes.length; // add it to the global array of all nodes
this.aNodes[nodeID] = aChild; // yep, passed by reference!

aChild.parent = oParent; // be good to your parents!

// **** this is where it starts to get tricky ****
if (!oParent.children) oParent.children = new Array();
var iN = oParent.children.length;
oParent.children[iN] = aChild; // <-- BANG there's the beginning of the problem

if (aChild.children.length > 0) { // if the child itself has kids, add those!
  this.renderChildren(aChild.children, aChild); // <-- BANG second part of the problem
}
  }
}

It might not be obvious but this function results in endless recursion when you specify a tree where any item in it has children because the children try to add themselves to their parents child array. The array condition of that main FOR loop is never satisfied because the child array just keeps growing.

BEFORE YOU SAY "well don't add it to the parent array...it's already there!" I'd like to point out that the step of adding a child to its parent's array of children is necessary because my tree will not necessarily load all its children at once and, to make a long story short, the arg supplied to this function isn't always a complete tree...sometimes its just a single set of sibling nodes with no reference to the parent object. a child must make sure it is included in its parent's child array.

Anyway...I was surprised by the recursion thing (although it seems obvious now) and have gotten around it by naming the child array something different in the arguments than it is in the data structure I'm building. I was wondering how other people might deal with this possibility of recursion.

    Write a Reply...