/
tree.js
64 lines (56 loc) · 1.44 KB
/
tree.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
56
57
58
59
60
61
62
63
64
var joinPaths = require('./path').join;
exports.lookup = lookup;
function traverse (tree, path, iter) {
var props = path.split('.')
, curr = tree
, currPath = ''
, prop
, next
, parent
;
while (prop = props.shift()) {
currPath = currPath ? currPath + '.' + prop : prop;
parent = curr;
curr = curr[prop];
// parts can be modified by iter(...)
next = iter(curr, currPath, props, parent);
currPath = next.path;
curr = next.node;
if (next.halt) break;
}
return {
node: curr
, path: joinPaths(currPath, props)
};
}
function lookup (tree, path, meta, ee) {
var getRef = meta && meta.getRef
, skipLast = meta && meta.skipLast
, prevRests = meta && meta.prevRests
;
if (skipLast && path.indexOf('.') === -1) {
return {
node: tree
, path: ''
};
}
return traverse(tree, path, function (node, pathToNode, rest, parent) {
if (! node) {
return {node: node, path: pathToNode, halt: true};
}
if (skipLast && rest.length === 1) var halt = true;
if (typeof node === 'function') {
if (getRef && ! rest.length) {
var out = {node: node, path: pathToNode};
if (halt) out.halt = true;
return out;
}
var out = node(tree, pathToNode, rest, ee, prevRests);
if (halt) out.halt = true;
return out;
}
var out = {node: node, path: pathToNode};
if (halt) out.halt = true;
return out;
});
}