This repository has been archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 510
/
Copy pathtree-iterator.js
55 lines (49 loc) · 1.9 KB
/
tree-iterator.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
var estraverse = require('estraverse');
var assign = require('lodash').assign;
var types = require('babel-core').types;
var keys = assign({}, types.VISITOR_KEYS, estraverse.VisitorKeys, {
// Those are deprecated, need to remove it in the future
XJSIdentifier: [],
XJSNamespacedName: ['namespace', 'name'],
XJSMemberExpression: ['object', 'property'],
XJSEmptyExpression: [],
XJSExpressionContainer: ['expression'],
XJSElement: ['openingElement', 'closingElement', 'children'],
XJSClosingElement: ['name'],
XJSOpeningElement: ['name', 'attributes'],
XJSAttribute: ['name', 'value'],
XJSSpreadAttribute: ['argument'],
XJSText: null,
// babel-core extends the estraverse "VisitorKeys" property with old TryStatement path
// We need to revert it back
TryStatement: ['block', 'handler', 'finalizer']
});
module.exports.iterate = function iterate(node, cb) {
if ('type' in node) {
estraverse.traverse(node, {
enter: function(node, parent) {
var parentCollection = [];
// parentCollection support
var path = this.path();
if (path) {
var collectionKey;
while (path.length > 0) {
var pathElement = path.pop();
if (typeof pathElement === 'string') {
collectionKey = pathElement;
break;
}
}
parentCollection = parent[collectionKey];
if (!Array.isArray(parentCollection)) {
parentCollection = [parentCollection];
}
}
if (cb(node, parent, parentCollection) === false) {
return estraverse.VisitorOption.Skip;
}
},
keys: keys
});
}
};