UNPKG

1.12 kBJavaScriptView Raw
1"use strict";
2
3const is = require("simple-is");
4
5function traverse(root, options) {
6 options = options || {};
7 const pre = options.pre;
8 const post = options.post;
9 const cleanup = options.cleanup;
10
11 function visit(node, parent) {
12 if (!node || !is.string(node.type)) {
13 return;
14 }
15
16 let res = undefined;
17 if (pre) {
18 res = pre(node, parent);
19 }
20
21 if (res !== false) {
22 for (let prop in node) {
23 if (prop[0] === "$") {
24 if (cleanup) {
25 delete node[prop];
26 }
27 continue;
28 }
29
30 const child = node[prop];
31
32 if (Array.isArray(child)) {
33 for (let i = 0; i < child.length; i++) {
34 visit(child[i], node);
35 }
36 } else {
37 visit(child, node);
38 }
39 }
40 }
41
42 if (post) {
43 post(node, parent);
44 }
45 }
46
47 visit(root, null);
48};
49module.exports = traverse;