/
util.skip-bundled.js
74 lines (69 loc) 路 1.87 KB
/
util.skip-bundled.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { parseSync, traverse, types as t } from "@babel/core";
import { traversePattern, privateKeyPathIterator } from "../lib/util.js";
function wrapSourceInClassEnvironment(input) {
const usedPrivateNames = new Set();
let matched;
const re = /#[\w_]+/g;
while ((matched = re.exec(input)) !== null) {
usedPrivateNames.add(matched[0]);
}
let result = "(class {";
for (const name of usedPrivateNames) {
result += name + ";";
}
result += "m(){ " + input + "}})";
return result;
}
function getPath(input, parserOpts = { plugins: ["destructuringPrivate"] }) {
let targetPath;
traverse(
parseSync(wrapSourceInClassEnvironment(input), {
parserOpts,
filename: "example.js",
configFile: false,
}),
{
Pattern(path) {
targetPath = path;
path.stop();
},
},
);
return targetPath;
}
describe("traversePattern", () => {
it("should visit property with private keys in depth-first order", () => {
const patternPath = getPath(
"const { #a: { #b: b, c, ...d }, e: [{ #c: [{ #d: { #c: g } }] }, ...{ #b: h }], #a: i } = obj;",
);
const keys = [
...traversePattern(patternPath.node, function* (node) {
if (t.isObjectProperty(node)) {
const propertyKey = node.key;
if (t.isPrivateName(propertyKey)) {
yield propertyKey.id.name;
}
}
}),
];
expect(keys).toEqual(["a", "b", "c", "d", "c", "b", "a"]);
});
});
describe("privateKeyPathIterator", () => {
const indexPaths = [
...privateKeyPathIterator(
getPath(
"const { #a: { a, #b: b, c, ...d }, e: [{ #c: [{ d: e, #d: { #c: f } }] }, ...{ #b: g }], #a: i } = obj;",
).node,
),
].map(indexPath => indexPath.join(","));
expect(indexPaths).toEqual([
"0",
"0,1",
"1,0,0",
"1,0,0,0,1",
"1,0,0,0,1,0",
"1,1,0,0",
"2",
]);
});