How to get the path to a leaf of the tree?
arielger opened this issue ยท 4 comments
I want to get the path to a leaf inside the tree. Do you have any recommended way to do this?
Similar to this method https://github.com/joaonuno/tree-model-js#get-the-node-path
Thanks for your work on this, great library ๐
I just solved it like this inside the crawl Iteratee callback, but I'm not sure if it's the best way:
crawl(tree, (node, context) => {
// add path to each node
node.path = context.cursor.stack.xs.reduce((result, item) => {
if (item.node) {
result.push(item.node);
}
return result;
}, []);
})
@arielger Thanks ๐
@jschroeter Yes, that would be how to do it! The DFS cursor basically holds that path in its stack.
I was initially exposing a Context#path
but I eventually removed it because tracking the path in BFS is more complex and I didn't want to do that by default as I'm focusing on performance for this library. So in order to stay consistent, I just removed it.
That said, it's a pretty common use case, so I guess I will mention how to do that in the readme
. If you have other suggestions, they are welcomed!
@ngryman Sadly, this doesn't seem to work anymore: https://codesandbox.io/s/tree-crawl-path-fc2hv6?file=/src/App.js