问题描述:

I need to find node by id in the tree. For that i am going down with help of two nested loops. But returned undefined.

function searchInTreeById(node, matchingId) {

var res;

if (node.select('id').get() == matchingId) {

res = node.get();

return res

} else {

if (node.exists('childObjects')) {

node.select('childObjects').map(function (cursor, i) {

cursor.select('children').map(function (cursorChild, j) {

if (cursorChild.select('id').get() === matchingId) {

// console.log(cursorChild.get()) //this console.log is execute

res = cursorChild.get();

return res;

} else {

// console.log(cursorChild.get())

searchInTreeById(cursorChild, matchingId)

}

})

})

} else {

res = node;

}

}

return res

}

网友答案:

When the match is not immediately found, you call recursively the function which should eventually return the result. But it does not.

searchInTreeById(cursorChild, matchingId);

However, using map will apply the check/function to every child, but the result is lost anyway, in this case. The map function applies the function given in parameters to the array elements, and return the new value for each element - a new array. Depending how quickly the item is found, a copy of the tree is built in memory (a traditional recursive function keeps only the path of elements up to a node).

So you could assign the map result to an array, which each element is set to null if that particular child didn't have a match, or the node if found. Then you check all elements of that created array, and return either null or node if found (then, the caller fills the array at that level etc...).

You could also use a global variable

var found = null;

only set when there is a match (nothing done otherwise). Since it seems a map is not breakable, the children at that level will be checked anyway. But, the difference is that before calling recursively the function again, you check the global variable, and call only if found is still null.

But maybe map could be avoided all together?

Instead of using map, gather the children in an array and iterate over that array, calling recursively the function, and return immediately the node matching.

Suggested code (not tested)

function searchInTreeById(node, matchingId) {
    if (node.select('id').get() == matchingId) {
        return node.get();
    }
    if (node.exists('childObjects')) {
         var list = node.select('childObjects');
         for(var i=0 ; i<list.length ; i++) {
             var res = searchInTreeById(list[i], matchingId);
             if (res) return res;
         }
     }
     return null;
}

Disclaimer: baobab first timer. (I read this though)

相关阅读:
Top