-
Notifications
You must be signed in to change notification settings - Fork 3
/
traverse.js
126 lines (103 loc) · 2.4 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
'use strict';
function skipFn() {
this._skip = true;
}
function removeFn() {
this._remove = true;
}
function nameFn(name) {
this._name = name;
}
function replaceFn(node) {
this._replace = node;
}
function traverse(origin, callbacks) {
const empty = function() {};
const enter = callbacks && callbacks.enter || empty;
const leave = callbacks && callbacks.leave || empty;
function rec(tree, parent) {
if (tree === undefined) return;
if (tree === null) return;
if (tree === true) return;
if (tree === false) return;
const node = {
attr: {},
full: tree
};
const cxt = {
name: nameFn,
skip: skipFn,
// break: breakFn,
remove: removeFn,
replace: replaceFn,
_name: undefined,
_skip: false,
// _break: false,
_remove: false,
_replace: undefined
};
let e1IsNotAnObject = true;
switch (Object.prototype.toString.call(tree)) {
case '[object String]':
case '[object Number]':
return;
case '[object Array]':
tree.some(function(e, i) {
if (i === 0) {
node.name = e;
return false;
}
if (i === 1) {
if (
Object.prototype.toString.call(e) === '[object Object]'
) {
e1IsNotAnObject = false;
node.attr = e;
}
return true;
}
});
enter.call(cxt, node, parent);
if (cxt._name) {
tree[0] = cxt._name;
}
if (cxt._replace) {
return cxt._replace;
}
if (cxt._remove) {
return null;
}
if (!cxt._skip) {
let index = 0;
let ilen = tree.length;
while (index < ilen) {
if ((index > 1) || ((index === 1) && e1IsNotAnObject)) {
const returnRes = rec(tree[index], node);
if (returnRes === null) {
tree.splice(index, 1);
ilen -= 1;
continue;
}
if (returnRes) {
tree[index] = returnRes;
}
}
index += 1;
}
leave.call(cxt, node, parent);
if (cxt._name) {
tree[0] = cxt._name;
}
if (cxt._replace) {
return cxt._replace;
}
if (cxt._remove) {
return null;
}
}
}
}
rec(origin, undefined);
}
module.exports = traverse;
/* eslint complexity: 0 */