Skip to content

Commit

Permalink
fix(iterator): fix FilterPredicate
Browse files Browse the repository at this point in the history
This changes the call to a `FilterPredicate` to more closely match the type.  It cannot match exactly, because the `array` differs.

IMO, it would make more sense to provide the object with `node` and `parent` as the first parameter of a `FilterPredicate`, but that'd be a breaking change.
  • Loading branch information
boneskull committed Sep 5, 2024
1 parent cd38708 commit ece56f4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
7 changes: 4 additions & 3 deletions js/src/traversal.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export function traverse(root, visitor) {
* @callback FilterPredicate
* @param {Node} node
* @param {number} index
* @param {Array<Node>} array
* @param {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} array
* @returns {boolean}
*/

Expand All @@ -107,10 +107,11 @@ export function traverse(root, visitor) {
* @param {Node} root The root AST node to traverse.
* @param {FilterPredicate} [filter] A filter function to determine which steps to
* return;
* @returns {IterableIterator<{node:Node,parent:Node|undefined,phase:TraversalPhase}>} An iterator over the AST.
* @returns {IterableIterator<{node: Node, parent?: Node, phase: TraversalPhase}>} An iterator over the AST.
*/
export function iterator(root, filter = () => true) {

/** @type {Array<{node: Node, parent?: Node, phase: TraversalPhase}>} */
const traversal = [];

traverse(root, {
Expand All @@ -122,5 +123,5 @@ export function iterator(root, filter = () => true) {
}
});

return traversal.filter(filter).values();
return traversal.filter(({node}, index, array) => filter(node, index, array)).values();
}
10 changes: 10 additions & 0 deletions js/tests/traversal.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,16 @@ describe("iterator()", () => {
]);
});

it("should iterate using a filter", () => {
const root = t.document(t.identifier("foo"));
const steps = [...iterator(root, node => node.type === "Document")];

expect(steps).to.deep.equal([
{ node: root, parent: undefined, phase: "enter" },
{ node: root, parent: undefined, phase: "exit" }
]);
});

});
});
});

0 comments on commit ece56f4

Please sign in to comment.