Start babel-types tests, add isNodesEquivalent (#3553)

This commit is contained in:
Henry Zhu 2016-11-15 14:24:20 -05:00 committed by GitHub
parent c36f523737
commit 6a6ec8785b
4 changed files with 79 additions and 1 deletions

View File

@ -12,5 +12,8 @@
"esutils": "^2.0.2",
"lodash": "^4.2.0",
"to-fast-properties": "^1.0.1"
},
"devDependencies": {
"babylon": "^6.8.2"
}
}

View File

@ -529,7 +529,8 @@ export {
isVar,
isSpecifierDefault,
isScope,
isImmutable
isImmutable,
isNodesEquivalent
} from "./validators";
export {

View File

@ -238,3 +238,47 @@ export function isImmutable(node: Object): boolean {
return false;
}
/**
* Check if two nodes are equivalent
*/
export function isNodesEquivalent(a, b) {
if (typeof a !== "object" || typeof a !== "object" || a == null || b == null) {
return a === b;
}
if (a.type !== b.type) {
return false;
}
const fields = Object.keys(t.NODE_FIELDS[a.type] || a.type);
for (let field of fields) {
if (typeof a[field] !== typeof b[field]) {
return false;
}
if (Array.isArray(a[field])) {
if (!Array.isArray(b[field])) {
return false;
}
if (a[field].length !== b[field].length) {
return false;
}
for (let i = 0; i < a[field].length; i++) {
if (!isNodesEquivalent(a[field][i], b[field][i])) {
return false;
}
}
continue;
}
if (!isNodesEquivalent(a[field], b[field])) {
return false;
}
}
return true;
}

View File

@ -0,0 +1,30 @@
var t = require("../lib");
var assert = require("assert");
var parse = require("babylon").parse;
suite("validators", function () {
suite("isNodesEquivalent", function () {
it("should handle simple cases", function () {
var mem = t.memberExpression(t.identifier("a"), t.identifier("b"));
assert(t.isNodesEquivalent(mem, mem) === true);
var mem2 = t.memberExpression(t.identifier("a"), t.identifier("c"));
assert(t.isNodesEquivalent(mem, mem2) === false);
});
it("should handle full programs", function () {
assert(t.isNodesEquivalent(parse("1 + 1"), parse("1+1")) === true);
assert(t.isNodesEquivalent(parse("1 + 1"), parse("1+2")) === false);
});
it("should handle complex programs", function () {
var program = "'use strict'; function lol() { wow();return 1; }";
assert(t.isNodesEquivalent(parse(program), parse(program)) === true);
var program2 = "'use strict'; function lol() { wow();return -1; }";
assert(t.isNodesEquivalent(parse(program), parse(program2)) === false);
});
});
});