Skip to content

Commit

Permalink
Add path sibling traversal methods
Browse files Browse the repository at this point in the history
* getPrevSibling
* getNextSibling
* forEachNextSibling
* forEachPrevSibling
  • Loading branch information
chitchu committed Jan 28, 2017
1 parent 446b4a7 commit bbdf71f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/babel-traverse/src/path/family.js
Expand Up @@ -67,6 +67,30 @@ export function getSibling(key) {
});
}

export function getPrevSibling() {
return this.getSibling(this.key - 1);
}

export function getNextSibling() {
return this.getSibling(this.key + 1);
}

export function forEachNextSibling(callback = Function.prototype) {
let _key = this.key, nextSibling = this.getSibling(++_key);
while (nextSibling.node) {
callback(nextSibling);
nextSibling = this.getSibling(++_key);
}
}

export function forEachPrevSibling(callback = Function.prototype) {
let _key = this.key, nextSibling = this.getSibling(--_key);
while (nextSibling.node) {
callback(nextSibling);
nextSibling = this.getSibling(--_key);
}
}

export function get(key: string, context?: boolean | TraversalContext): NodePath {
if (context === true) context = this.context;
const parts = key.split(".");
Expand Down
24 changes: 24 additions & 0 deletions packages/babel-traverse/test/family.js
Expand Up @@ -52,6 +52,30 @@ describe("path/family", function () {
assert.strictEqual(outerNodes[id], outerPaths[id].node, "nodes match");
});
});

});
describe("getSibling", function () {
const ast = parse("var a = 1, {b} = c, [d] = e; function f() {}");
let sibling = {};
traverse(ast, {
VariableDeclaration(path) {
sibling = path.getSibling(path.key);
}
});
it("should return traverse sibling nodes", function () {
assert.strictEqual(!!sibling.getNextSibling().node, true, "has property node");
assert.strictEqual(!!sibling.getNextSibling().getPrevSibling().node, true, "has property node");
let nextSiblings = 0, prevSiblings = 0;
sibling.forEachNextSibling(() => {
nextSiblings++;
});
assert.strictEqual(!!nextSiblings, true, "Has next sibling");

sibling.getNextSibling().forEachPrevSibling(() => {
prevSiblings++;
});
assert.strictEqual(!!prevSiblings, true, "Has prev sibling");
});
});
});

Expand Down

0 comments on commit bbdf71f

Please sign in to comment.