Skip to content

Commit 09800f8

Browse files
committed
📚 mention how to get a node's path
Thanks to @arielger for mentioning this and @jschroeter for posting a solution!
1 parent c640f71 commit 09800f8

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

readme.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,26 @@ crawl(tree, (node, context) => {
8484
})
8585
```
8686

87+
## FAQ
88+
89+
### How can I get the path of the current node ([#37](https://github.com/ngryman/tree-crawl/issues/37))?
90+
91+
**tl;dr It's easy for DFS, less easy for BFS**
92+
93+
If you are using DFS you can use the following utility function:
94+
```
95+
const = getPath(context) =>
96+
context.cursor.stack.xs.reduce((path, item) => {
97+
if (item.node) {
98+
path.push(item.node)
99+
}
100+
return path
101+
})
102+
```
103+
If you are really concerned about performance, you could read items from the stack directly. Each item has a `node` and `index` property that you can use. The first item in the stack can be discarded and will have a `node` set to `null`. Be aware that you should not mutate the stack, or it will break the traversal.
104+
105+
If you are using BFS, things gets more complex. A *simple hacky* way to do so is to traverse the tree using DFS first. You can ad a `path` property to your nodes using the method above. And then do your regular BFS traversal using that `path` property.
106+
87107
## API
88108

89109
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

0 commit comments

Comments
 (0)