Returning to FORTRAN days that did not support recursion, one achieved similar effects by modifying the data set to mimic the level of βrecursionβ. Applying this principle to the approximate structure of an object, the function of searching for an object by its "pseudonym" (name or identifier in another word) can be written without recursion as follows:
function findAlias( parent, alias) // parent object, alias value string { function frame( parent) { return {parent: parent, children: parent.children, index: 0, length: parent.children.length}; } var stack, tos, child, children, i; stack = []; if( parent.children) stack.push( frame( parent)); search: while( stack.length) { tos = stack.pop();
In short, it creates a stack of small data objects that are popped and popped into the same function instead of making recursive calls. The above example returns an object with parent and child objects. The child value is the value with the alias provided, and the parent with the child in the children array.
It returns null if the alias cannot be found, so it can be used for hasAlias . If it does not return null, it executes the getParent functionality. However, you need to create a root node:
// create a rootnode var rootNode = { alias: "root", children: exampleArray}; var found = findAlias(rootNode, "alias3"); if( found) { console.log("%s is a child of %s, childIndex = %s", found.child.alias, found.parent.alias, found.childIndex); } else console.log("not found");
[Edit: add childIndex to search for the return object, update the sample code example, add output.]
Conclusion
Using recursive function calls, when supported for a tree-walking application, makes sense in terms of self-documenting code and maintainability. A non-recursive option may pay for this if it can be shown that it has significant advantages in reducing server load during volume pressure tests, but requires sound documentation.
Regardless of internal coding, the tree-walking function, which returns an object with details of the values ββof the parent, child, and child indexes, can contribute to the overall efficiency of the program by reducing the total number of triples performed:
- the validity of the returned search value replaces the
hasAlias function - a return from search object can be transferred to update, delete, or insert functions without having to search the trees in each function again.