Skip to content

Commit

Permalink
Add path sibling traversal methods
Browse files Browse the repository at this point in the history
* getPrevSibling
* getNextSibling
* getAllNextSiblings
* getAllPrevSiblings
  • Loading branch information
chitchu committed Jan 31, 2017
1 parent 2104ab6 commit 3a42557
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
31 changes: 31 additions & 0 deletions packages/babel-traverse/src/path/family.js
Expand Up @@ -67,6 +67,37 @@ export function getSibling(key) {
});
}

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

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

export function getAllNextSiblings() {
let _key = this.key;
let sibling = this.getSibling(++_key);
const siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(++_key);
}
return siblings;
}

export function getAllPrevSiblings() {
let _key = this.key;
let sibling = this.getSibling(--_key);
const siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(--_key);
}
return siblings;
}


export function get(key: string, context?: boolean | TraversalContext): NodePath {
if (context === true) context = this.context;
const parts = key.split(".");
Expand Down
22 changes: 22 additions & 0 deletions packages/babel-traverse/test/family.js
Expand Up @@ -52,6 +52,28 @@ 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.ok(sibling.getNextSibling().node, "has property node");
assert.ok(sibling.getNextSibling().getPrevSibling().node, "has property node");
assert.equal(!!sibling.getPrevSibling().node, false, "out of scope");
assert.equal(!!sibling.getNextSibling().getNextSibling().node, false, "out of scope");
});

it("should return all preceding and succeeding sibling nodes", function () {
assert.ok(sibling.getAllNextSiblings().length, "Has next sibling");
assert.ok(sibling.getNextSibling().getAllPrevSiblings().length, "Has prev sibling");
});
});
});

Expand Down

0 comments on commit 3a42557

Please sign in to comment.