Walk unist trees with enter and leave functions
npm install unist-util-walkerInspired by estree-walker, this package provides a method to walk unist trees, by providing an enter and leave function.
The main advantage over unist-util-visit is that we can enter all child nodes and accumulate data,
which we can then use in the leave function of the parent.
bash
npm install unist-util-walker
`$3
`bash
yarn add unist-util-walker
`$3
`bash
pnpm add unist-util-walker
`Usage
`typescript
import type { Node, Parent } from 'unist';
import { walk } from 'unist-util-walker';
import { u } from 'unist-builder';const tree: Node = u('root', [
u('subtree', {id: 1}),
u('subtree', {id: 2}, [
u('node', [u('leaf', {id: 1}), u('leaf', {id: 2})]),
u('leaf', {id: 3}),
u('void'),
]),
]);
walk(tree, {
enter(node: Node, parent?: Parent, index?: number) {
// some code happens
},
leave(node: Node, parent?: Parent, index?: number) {
// some code happens
}
});
`Inside of the
enter and leave functions, you can call the following functions:-
this.break()
Skips children and the leave function of the current node (only useful in enter).
- this.skip()
Skips children, but still runs the leave function of the current node (only useful in enter).
- this.remove()
Removes the node from the tree (has no effect on root node).
- this.replace(node: Node)`