ngryman/tree-crawl

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!

Added an FAQ section in the readme in 09800f8.