There's a problem with your algorithm. Both your if
and your else
return unconditionally, which means that a return
will inevitably occur on the first iteration through each loop, and the algorithm will only check the first of each of its descendants (in this case just nodes 4 and 1 and nothing else). You need to check whether the recursive call returned a found value, and only pass that up the recursive tree if so. I think this should provide you a fixed solution:
myClass.prototype.nodeSearch = function nodeSearch(treeNodes, searchID){
for (var nodeIdx = 0; nodeIdx <= treeNodes.length-1; nodeIdx++) {
var currentNode = treeNodes[nodeIdx],
currentId = currentNode.id,
currentChildren = currentNode.children;
console.log("Comparing treeNodes element with ID==" +
currentId + " to SearchID==" + searchID);
if (currentId == searchID) {
console.log("Match!");
return currentNode;
}
else {
console.log("No Match! Trying " + currentChildren.length +
" Children of Node ID#" + currentId);
var foundDescendant = this.nodeSearch(currentChildren, searchID);
if (foundDescendant) {
return foundDescendant;
}
}
}
console.log("Done trying " + treeNodes.length + " children. Returning False");
return false;
};
I've also added some variables to help make the code a bit DRYer and help prevent some of the bugs mentioned earlier.