forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast-utils.js
More file actions
62 lines (53 loc) · 1.45 KB
/
ast-utils.js
File metadata and controls
62 lines (53 loc) · 1.45 KB
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
import isObject from "./is-object.js";
/**
* @typedef {NonNullable<object>} Node
* @typedef {(unknown) => string[]} GetVisitorKeys
* @typedef {(unknown) => boolean} Predicate
*/
/**
* @param {Node} node
* @param {{getVisitorKeys: GetVisitorKeys, filter?: Predicate}} options
*/
function* getChildren(node, options) {
const { getVisitorKeys, filter = () => true } = options;
const isMatchedNode = (node) => isObject(node) && filter(node);
for (const key of getVisitorKeys(node)) {
const value = node[key];
if (Array.isArray(value)) {
for (const child of value) {
if (isMatchedNode(child)) {
yield child;
}
}
} else if (isMatchedNode(value)) {
yield value;
}
}
}
/**
* @param {Node} node
* @param {{getVisitorKeys: GetVisitorKeys, filter?: Predicate}} options
*/
function* getDescendants(node, options) {
const queue = [node];
for (let index = 0; index < queue.length; index++) {
const node = queue[index];
for (const child of getChildren(node, options)) {
yield child;
queue.push(child);
}
}
}
/**
* @param {Node} node
* @param {{getVisitorKeys: GetVisitorKeys, predicate: Predicate}} options
*/
function hasDescendant(node, { getVisitorKeys, predicate }) {
for (const descendant of getDescendants(node, { getVisitorKeys })) {
if (predicate(descendant)) {
return true;
}
}
return false;
}
export { getChildren, getDescendants, hasDescendant };