You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This PR is a small improvement of the current `walk` implementation
where we will expose the `index` and the `siblings` on the current
context.
During a walk, we walk over objects that contain a `nodes: []` field.
The `ctx.parent` that already exists is a reference to the parent node,
but `ctx.siblings` is a reference to the `ctx.parent.nodes`.
The `ctx.index` is the index of the current node we are walking in the
`siblings` array. This way we can prevent the awkward
`ctx.parent?.nodes.indexOf(node)` which is a bit silly because we
already know the nodes we're walking and its index...
The `ctx.parent` can be `null`, but the `ctx.siblings` will never be
`null`, this can be seen in a situation like this:
```ts
let ast: AstNode = [nodeA, nodeB]
walk(ast, (node, ctx) => {
if (node === nodeA) {
ctx.parent === null; // Because there is no parent
ctx.siblings === ast; // Because that's the current list we're looping over
// Before this PR, we would have to do something like:
let siblings = ctx.parent?.nodes ?? ast
}
})
```
In the above example, the `ast` is a separately variable, but if this
was inlined, we would run into some issues:
```ts
walk([nodeA, nodeB], (node, ctx) => {
if (node === nodeA) {
ctx.parent === null; // Because there is no parent
ctx.siblings === ast; // Because that's the current list we're looping over
// At this point, there is no way to get to the `[nodeA, nodeB]` list
// without moving it to a variable first.
}
})
```
So, this PR doesn't change much, the additional information we track is
already known information that is now exposed to the caller of the
`walk` function.
In this PR we did update some usages and got rid of some awkward
`ctx.parent?.nodes ?? []` and `ctx.parent.nodes.indexOf(…)` usages.
## Test plan
- All tests still pass as expected
0 commit comments