-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
91 lines (78 loc) · 1.87 KB
/
index.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
exports.parse = function(lines, marker) {
var populatefn = populatefn || function(obj) { return obj;};
var marker = marker || '\t';
function addHiddenProperties(scope, props) {
for (p in props) {
Object.defineProperty(scope, p, {enumerable: false, value: props[p]});
}
}
var TreeNode = function(data, depth) {
this.parent = null;
addHiddenProperties(this, {
'data':data,
'depth':depth,
'parent':null,
'children':[]
});
this[data||'root']=this.children;
}
TreeNode.prototype.toString = function() {
return JSON.stringify(this.children);
}
var tree = new TreeNode(null, -1);
var levels = [tree];
function countTabs(line) {
var count = 0;
for (var i = 0; i < line.length; i++) {
var ch = line[i];
if ((ch == '\t')) {
count += 1;
}else if (/[^\s]/.test(ch)){
return count;
}
}
return -1; // no content
}
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var tabcount = countTabs(line);
if (tabcount >= 0) { //then add node to tree
function topnode() {
return levels[levels.length - 1];
}
while(tabcount - topnode().depth <= 0) {
levels.pop();
}
var depth = levels.length - 1;
var node = new TreeNode(line.substring(tabcount), depth);
node.parent = topnode();
node.parent.children.push(node);
levels.push(node);
}
}
return tree;
}
exports.traverse = function (tree, cb){
function _traverse(node) {
cb(node);
for (var i = 0; i < node.children.length; i++) {
_traverse(node.children[i]);
}
}
for (var i = 0; i < tree.children.length; i++) {
_traverse(tree.children[i]);
}
}
exports.print = function(tree) {
exports.traverse(tree, function(node) {
var string = "";
for (var i = 0; i < node.depth; i++) {
string += "\t";
}
string += node.data;
console.log(string);
});
}
exports.toJSON = function(tree) {
return JSON.stringify(tree.children);
}