-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtoJSON.js
More file actions
50 lines (39 loc) · 1.12 KB
/
toJSON.js
File metadata and controls
50 lines (39 loc) · 1.12 KB
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
Array.prototype.last = function() {
if (this.length == 0) return undefined;
return this[this.length-1];
};
const rl = require('readline').createInterface({
input: process.stdin
});
var tree = [];
var stack = [tree];
var lastDepth = 0;
var currentNode = function() {
return stack.last();
}
function validateDepth(depth, lastDepth) {
if (depth - lastDepth > 1) throw new Error("Invalid format, can't jump more than one tab in");
}
rl.on('line', (line) => {
var name = line.trim();
if (name.length == 0) return;
var depth = (line.match(/^\t*/))[0].length;
var moreDeep = depth > lastDepth;
var shallower = depth < lastDepth;
if (moreDeep) {
validateDepth(depth, lastDepth); // check the format is valid
// convert the last line to a "parent" node
var parent = currentNode().last();
parent.children = [];
// Make that line's children the "current node"
stack.push( parent.children );
} else if (shallower) {
var pops = lastDepth - depth;
while (pops--) stack.pop();
}
lastDepth = depth;
currentNode().push( { name: name } );
});
rl.on('close', () => {
console.log(JSON.stringify(tree, undefined, " "));
})