forked from JacksonTian/fks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.js
85 lines (73 loc) · 1.89 KB
/
generate.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
var fs = require('fs');
var path = require('path');
var readme = fs.readFileSync(path.join(__dirname, '../README.md'), 'utf8');
var getItems = function (str) {
var patt = /([ ]*)-(.*)/g;
var result;
var list = [];
while ((result = patt.exec(str)) != null) {
list.push({level: result[1].length / 4, content: result[2].trim()});
}
return list;
};
var filter = function (list) {
var j = 0;
var f2e = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
if (item.level === 0) {
j = j + 1;
if (j === 2) {
break;
}
}
f2e.push(item);
}
return f2e;
};
var format = function (list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
var data = {
id: '' + i,
name: item.content,
level: item.level
};
result.push(data);
}
return result;
};
var items = getItems(readme);
var f2e = filter(items);
var formated = format(f2e);
var buildTree = function (list) {
var root = null;
for (var i = 0; i < list.length; i++) {
var item = list[i];
if (root === null) {
root = item;
root.children = [];
}
var lastLevel0 = root.children;
if (item.level === 1) {
delete item.level;
lastLevel0.push(item);
}
if (item.level === 2) {
var lastLevel1 = lastLevel0[lastLevel0.length - 1];
lastLevel1.children = lastLevel1.children || [];
lastLevel1.children.push(item);
}
if (item.level === 3) {
var lastLevel1Child = lastLevel0[lastLevel0.length - 1].children;
var lastLevel2 = lastLevel1Child[lastLevel1Child.length - 1];
lastLevel2.children = lastLevel2.children || [];
lastLevel2.children.push(item);
}
delete item.level;
}
return root;
};
var tree = buildTree(formated);
fs.writeFileSync(path.join(__dirname, '../fks_chart/data/front-end.json'), JSON.stringify(tree, null, ' '));