UNPKG

998 BJavaScriptView Raw
1'use strict';
2
3/* Expose. */
4module.exports = visit;
5
6/* Visit. */
7function visit(tree, type, visitor, reverse) {
8 if (typeof type === 'function') {
9 reverse = visitor;
10 visitor = type;
11 type = null;
12 }
13
14 one(tree);
15
16 /* Visit a single node. */
17 function one(node, index, parent) {
18 var result;
19
20 index = index || (parent ? 0 : null);
21
22 if (!type || node.type === type) {
23 result = visitor(node, index, parent || null);
24 }
25
26 if (node.children && result !== false) {
27 return all(node.children, node);
28 }
29
30 return result;
31 }
32
33 /* Visit children in `parent`. */
34 function all(children, parent) {
35 var step = reverse ? -1 : 1;
36 var max = children.length;
37 var min = -1;
38 var index = (reverse ? max : min) + step;
39 var child;
40
41 while (index > min && index < max) {
42 child = children[index];
43
44 if (child && one(child, index, parent) === false) {
45 return false;
46 }
47
48 index += step;
49 }
50
51 return true;
52 }
53}