Add path utilities isAncestor and isDescendant (#4836)

* Add path utilities isAncestor and isDescendant

* Create ancestry.js
This commit is contained in:
Boopathi Rajaa 2016-11-15 22:36:45 +01:00 committed by Henry Zhu
parent f8ddd80f96
commit 55a47a8819
2 changed files with 79 additions and 0 deletions

View File

@ -175,6 +175,20 @@ export function getAncestry() {
return paths;
}
/**
* A helper to find if `this` path is an ancestor of @param maybeDescendant
*/
export function isAncestor(maybeDescendant) {
return !!maybeDescendant.findParent((parent) => parent === this);
}
/**
* A helper to find if `this` path is a descendant of @param maybeAncestor
*/
export function isDescendant(maybeAncestor) {
return maybeAncestor.isAncestor(this);
}
export function inType() {
let path = this;
while (path) {

View File

@ -0,0 +1,65 @@
let traverse = require("../lib").default;
let assert = require("assert");
let parse = require("babylon").parse;
describe("path/ancestry", function () {
describe("isAncestor", function () {
let ast = parse("var a = 1; 'a';");
it("returns true if ancestor", function() {
let paths = [];
traverse(ast, {
"Program|NumericLiteral"(path) {
paths.push(path);
},
});
let [ programPath, numberPath ] = paths;
assert(programPath.isAncestor(numberPath));
});
it("returns false if not ancestor", function() {
let paths = [];
traverse(ast, {
"Program|NumericLiteral|StringLiteral"(path) {
paths.push(path);
}
});
let [ , numberPath, stringPath ] = paths;
assert(!stringPath.isAncestor(numberPath));
});
});
describe("isDescendant", function () {
let ast = parse("var a = 1; 'a';");
it("returns true if descendant", function() {
let paths = [];
traverse(ast, {
"Program|NumericLiteral"(path) {
paths.push(path);
},
});
let [ programPath, numberPath ] = paths;
assert(numberPath.isDescendant(programPath));
});
it("returns false if not descendant", function() {
let paths = [];
traverse(ast, {
"Program|NumericLiteral|StringLiteral"(path) {
paths.push(path);
}
});
let [ , numberPath, stringPath ] = paths;
assert(!numberPath.isDescendant(stringPath));
});
});
});