1

I have a function I'm using to recurse through a series of nested, tree node-like objects. Based on the console output, I can tell that all nodes are currently being visited. Here's the function:

function directoryRecurse(dir, searchedPath) {
    for (var ii = 0; ii < dir.children.length; ii++) {
        if (dir.children[ii].path && dir.children[ii].path === searchedPath) {
            return dir.children[ii];
        } else {
            directoryRecurse(dir.children[ii], searchedPath);
        }
    }
}

However, the return value is always undefined. I've tried modifying the function so that directoryRecurse(dir.children[ii], searchedPath) is replaced with return directoryRecurse(dir.children[ii], searchedPath), but in this case the function terminates after the first leaf node is found. How do I ensure all nodes are visited and that the final return value is the node being searched for?

kurfle
  • 15
  • 5

1 Answers1

0

So directoryRecurse returns a dir if a match is found, and 'undefined' if no match is found... so you need to check which in your recursive call:

function directoryRecurse(dir, searchedPath) {
    for (var ii = 0; ii < dir.children.length; ii++) {
        if (dir.children[ii].path && dir.children[ii].path === searchedPath) {
            return dir.children[ii];
        } else {
            var result = directoryRecurse(dir.children[ii], searchedPath);
            if (typeof result != 'undefined') {
                return result;
            }
        }
    }
}

Not sure of the Javascript syntax for result !== undefined, so anyone who knows feel free to correct.

Update: I think this answer (How to check for "undefined" in JavaScript?) suggests typeof for this case of undefined, so updated accordingly.

Community
  • 1
  • 1
Barney
  • 2,786
  • 2
  • 32
  • 34
  • This is perfect - thanks so much. Javascript is a little different than the rest of my experience in terms of returning from recursion. – kurfle Feb 16 '15 at 06:52