-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraverser.ts
38 lines (30 loc) · 865 Bytes
/
traverser.ts
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
import { NodeTypes } from './utils/type'
export function traverser(ast: any, visitor: any) {
// 遍历树结构 深度优先算法
function traverseArray(array: any, parent: any) {
array.forEach((child: any) => {
traverseNode(child, parent)
})
}
function traverseNode(node, parent) {
const methods = visitor[node.type]
if (methods && methods.enter)
methods.enter(node, parent)
switch (node.type) {
case NodeTypes.Program:
traverseArray(node.body, node)
break
case NodeTypes.CallExpression:
traverseArray(node.params, node)
break
case NodeTypes.NumberLiteral:
case NodeTypes.StringLiteral:
break
default:
throw new TypeError(node.type)
}
if (methods && methods.exit)
methods.exit(node, parent)
}
traverseNode(ast, null)
}