Skip to content

Visitor: fix description of "ancestors" arg + test #1250

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

Merged
merged 2 commits into from
May 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion src/language/__tests__/visitor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ describe('Visitor', () => {
checkVisitorFnArgs(ast, arguments);
visited.push(['enter', path.slice()]);
},

leave(node, key, parent, path) {
checkVisitorFnArgs(ast, arguments);
visited.push(['leave', path.slice()]);
Expand All @@ -95,6 +94,34 @@ describe('Visitor', () => {
]);
});

it('validates ancestors argument', () => {
const ast = parse('{ a }', { noLocation: true });
const visitedNodes = [];

visit(ast, {
enter(node, key, parent, path, ancestors) {
const inArray = typeof key === 'number';
if (inArray) {
visitedNodes.push(parent);
}
visitedNodes.push(node);

const expectedAncestors = visitedNodes.slice(0, -2);
expect(ancestors).to.deep.equal(expectedAncestors);
},
leave(node, key, parent, path, ancestors) {
const expectedAncestors = visitedNodes.slice(0, -2);
expect(ancestors).to.deep.equal(expectedAncestors);

const inArray = typeof key === 'number';
if (inArray) {
visitedNodes.pop();
}
visitedNodes.pop();
},
});
});

it('allows editing a node both on enter and on leave', () => {
const ast = parse('{ a, b, c { a, b, c } }', { noLocation: true });

Expand Down
4 changes: 2 additions & 2 deletions src/language/visitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ export type VisitFn<TAnyNode, TVisitedNode: TAnyNode = TAnyNode> = (
parent: TAnyNode | $ReadOnlyArray<TAnyNode> | void,
// The key path to get to this node from the root node.
path: $ReadOnlyArray<string | number>,
// All nodes and Arrays visited before reaching this node.
// All nodes and Arrays visited before reaching parent of this node.
// These correspond to array indices in `path`.
// Note: ancestors includes arrays which contain the visited node.
// Note: ancestors includes arrays which contain the parent of visited node.
ancestors: $ReadOnlyArray<TAnyNode | $ReadOnlyArray<TAnyNode>>,
) => any;

Expand Down