-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
massage-ast.js
52 lines (41 loc) · 1.24 KB
/
massage-ast.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
import createGetVisitorKeysFunction from "./create-get-visitor-keys-function.js";
function massageAst(ast, options) {
const {
printer: {
massageAstNode: cleanFunction,
getVisitorKeys: printerGetVisitorKeys,
},
} = options;
if (!cleanFunction) {
return ast;
}
const getVisitorKeys = createGetVisitorKeysFunction(printerGetVisitorKeys);
const ignoredProperties = cleanFunction.ignoredProperties ?? new Set();
return recurse(ast);
function recurse(original, parent) {
if (!(original !== null && typeof original === "object")) {
return original;
}
if (Array.isArray(original)) {
return original.map((child) => recurse(child, parent)).filter(Boolean);
}
const cloned = {};
const childrenKeys = new Set(getVisitorKeys(original));
for (const key in original) {
if (!Object.hasOwn(original, key) || ignoredProperties.has(key)) {
continue;
}
if (childrenKeys.has(key)) {
cloned[key] = recurse(original[key], original);
} else {
cloned[key] = original[key];
}
}
const result = cleanFunction(original, cloned, parent);
if (result === null) {
return;
}
return result ?? cloned;
}
}
export default massageAst;