/
traverseFast.js
54 lines (43 loc) 路 1.38 KB
/
traverseFast.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
// @flow
import { VISITOR_KEYS } from "../definitions";
// This workaround is needed because BabelNode doesn't have a "type" property,
// which is only defined by its subclasses.
type _Node<T: BabelNode & { type: string }> = T;
type Node = _Node<*>;
opaque type Stop = Symbol;
type EnterCallback = (node: Node, opts?: Object, parent?: Node) => Stop | void;
type TraverseFast = {
(node: Node, enter: EnterCallback, opts?: Object): void,
STOP: Stop,
};
const STOP: Stop = Symbol("traverseFast.STOP");
/**
* A prefix AST traversal implementation meant for simple searching
* and processing.
*
* If the visitor returns traverseFast.STOP, the traversal stops.
*/
export default (Object.assign(
function traverseFast(node, enter, opts) {
// Wrap this function to no return "STOP"
_traverseFast(node, null, enter, opts);
},
{ STOP },
): TraverseFast);
function _traverseFast(node, parent, enter, opts): Stop | void {
if (!node) return;
const keys = VISITOR_KEYS[node.type];
if (!keys) return;
opts = opts || {};
if (enter(node, opts, parent) === STOP) return STOP;
for (const key of keys) {
const subNode = node[key];
if (Array.isArray(subNode)) {
for (const child of subNode) {
if (_traverseFast(child, node, enter, opts) === STOP) return STOP;
}
} else {
if (_traverseFast(subNode, node, enter, opts) === STOP) return STOP;
}
}
}