UNPKG

1.05 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
10 function visit(node, parent) {
11 if (!node || !is.string(node.type)) {
12 return;
13 }
14
15 if (!is.own(node, "$parent")) {
16 node.$parent = parent;
17 }
18
19 let res = undefined;
20 if (pre) {
21 res = pre(node);
22 }
23
24 if (res !== false) {
25 for (let prop in node) {
26 if (prop[0] === "$") {
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);
44 }
45 }
46
47 visit(root, null);
48};
49module.exports = traverse;