Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get the path to a leaf of the tree? #37

Closed
arielger opened this issue Feb 23, 2018 · 4 comments
Closed

How to get the path to a leaf of the tree? #37

arielger opened this issue Feb 23, 2018 · 4 comments

Comments

@arielger
Copy link

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 👌

@jschroeter
Copy link

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;
  }, []);
})

@ngryman
Copy link
Owner

ngryman commented Feb 28, 2018

@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
Copy link
Owner

ngryman commented Feb 28, 2018

Added an FAQ section in the readme in 09800f8.

@ngryman ngryman closed this as completed Sep 13, 2018
@Lambdaphile
Copy link

@ngryman Sadly, this doesn't seem to work anymore: https://codesandbox.io/s/tree-crawl-path-fc2hv6?file=/src/App.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants