-
-
Notifications
You must be signed in to change notification settings - Fork 225
/
bfs-traverse.js
48 lines (40 loc) · 1.08 KB
/
bfs-traverse.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
"use strict";
module.exports = function bfsTraverseCreator({ types: t, traverse }) {
function getFields(path) {
return t.VISITOR_KEYS[path.type];
}
return function bfsTraverse(path, _visitor) {
if (!path.node) {
throw new Error("Not a valid path");
}
const visitor = traverse.explode(_visitor);
const queue = [path];
let current;
while (queue.length > 0) {
current = queue.shift();
// call
if (
visitor &&
visitor[current.type] &&
Array.isArray(visitor[current.type].enter)
) {
const fns = visitor[current.type].enter;
for (const fn of fns) {
if (typeof fn === "function") fn(current);
}
}
const fields = getFields(current);
for (const field of fields) {
const child = current.get(field);
if (Array.isArray(child)) {
// visit container left to right
for (const c of child) {
if (c.node) queue.push(c);
}
} else {
if (child.node) queue.push(child);
}
}
}
};
};