Add path utilities isAncestor and isDescendant (#4836)
* Add path utilities isAncestor and isDescendant * Create ancestry.js
This commit is contained in:
parent
f8ddd80f96
commit
55a47a8819
@ -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) {
|
||||
|
||||
65
packages/babel-traverse/test/ancestry.js
Normal file
65
packages/babel-traverse/test/ancestry.js
Normal 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));
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user