Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/tools/sass-variable-explainer/ast-utils.ts
6433 views
1
export const walk = (node: any, cb: (node: any) => unknown) => {
2
if (!node || typeof node !== "object") return;
3
if (!cb(node)) {
4
return;
5
};
6
for (const key of Object.keys(node)) {
7
walk(node[key], cb);
8
}
9
}
10
11
export const withType = (node: any, func: (ast: any) => any) => {
12
if (!node?.type) {
13
return node;
14
}
15
return func(node);
16
}
17
18
export const withTypeAndArray = (node: any, func: (ast: any) => any) => {
19
if (!node?.type) {
20
return node;
21
}
22
if (!node?.children || !Array.isArray(node.children)) {
23
return node;
24
}
25
return func(node);
26
}
27
28
export const filterDeep = (outer: any, cb: (v: any) => boolean): any =>
29
withType(outer, (ast: any) => {
30
return Object.fromEntries(Object.entries(ast).map(([k, v]) => {
31
if (Array.isArray(v)) {
32
return [k, v.filter(cb).map((v: any) => filterDeep(v, cb))];
33
} else if (v && typeof v === "object") {
34
return [k, filterDeep(v, cb)];
35
} else {
36
return [k, v];
37
}
38
}));
39
});
40
41
export const mapDeep = (outer: any, cb: (mapped: any) => any): any =>
42
withType(outer, (ast: any) => {
43
if (Array.isArray(ast.children)) {
44
ast.children = ast.children.map((v: any) => mapDeep(v, cb));
45
}
46
if (Array.isArray(ast.value)) {
47
ast.value = ast.value.map((v: any) => mapDeep(v, cb));
48
}
49
return cb(ast);
50
});
51
52
export const collect = (outer: any, cb: (v: any) => boolean): any[] => {
53
const results: any = [];
54
walk(outer, (node: any) => {
55
if (cb(node)) {
56
results.push(node);
57
}
58
return true;
59
});
60
return results;
61
}
62
63
export const annotateNode = (node: any, annotation: Record<string, unknown>) => {
64
if (!node.annotation) {
65
node.annotation = {};
66
}
67
Object.assign(node.annotation, annotation);
68
return node;
69
}
70