source: frontend/node_modules/estree-walker/src/estree-walker.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 2.3 KB
RevLine 
[9af201e]1function walk(ast, { enter, leave }) {
2 return visit(ast, null, enter, leave);
3}
4
5let should_skip = false;
6let should_remove = false;
7let replacement = null;
8const context = {
9 skip: () => should_skip = true,
10 remove: () => should_remove = true,
11 replace: (node) => replacement = node
12};
13
14function replace(parent, prop, index, node) {
15 if (parent) {
16 if (index !== null) {
17 parent[prop][index] = node;
18 } else {
19 parent[prop] = node;
20 }
21 }
22}
23
24function remove(parent, prop, index) {
25 if (parent) {
26 if (index !== null) {
27 parent[prop].splice(index, 1);
28 } else {
29 delete parent[prop];
30 }
31 }
32}
33
34function visit(
35 node,
36 parent,
37 enter,
38 leave,
39 prop,
40 index
41) {
42 if (node) {
43 if (enter) {
44 const _should_skip = should_skip;
45 const _should_remove = should_remove;
46 const _replacement = replacement;
47 should_skip = false;
48 should_remove = false;
49 replacement = null;
50
51 enter.call(context, node, parent, prop, index);
52
53 if (replacement) {
54 node = replacement;
55 replace(parent, prop, index, node);
56 }
57
58 if (should_remove) {
59 remove(parent, prop, index);
60 }
61
62 const skipped = should_skip;
63 const removed = should_remove;
64
65 should_skip = _should_skip;
66 should_remove = _should_remove;
67 replacement = _replacement;
68
69 if (skipped) return node;
70 if (removed) return null;
71 }
72
73 for (const key in node) {
74 const value = (node )[key];
75
76 if (typeof value !== 'object') {
77 continue;
78 }
79
80 else if (Array.isArray(value)) {
81 for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
82 if (value[j] !== null && typeof value[j].type === 'string') {
83 if (!visit(value[j], node, enter, leave, key, k)) {
84 // removed
85 j--;
86 }
87 }
88 }
89 }
90
91 else if (value !== null && typeof value.type === 'string') {
92 visit(value, node, enter, leave, key, null);
93 }
94 }
95
96 if (leave) {
97 const _replacement = replacement;
98 const _should_remove = should_remove;
99 replacement = null;
100 should_remove = false;
101
102 leave.call(context, node, parent, prop, index);
103
104 if (replacement) {
105 node = replacement;
106 replace(parent, prop, index, node);
107 }
108
109 if (should_remove) {
110 remove(parent, prop, index);
111 }
112
113 const removed = should_remove;
114
115 replacement = _replacement;
116 should_remove = _should_remove;
117
118 if (removed) return null;
119 }
120 }
121
122 return node;
123}
124
125export { walk };
Note: See TracBrowser for help on using the repository browser.