-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunction-id-parser.js
79 lines (62 loc) · 2.12 KB
/
function-id-parser.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
/* jshint esversion: 6 */
/* global __dirname */
(() => {
'use strict';
/**
* Parses a list of function ids from txt file.
*/
const fs = require('fs');
const request = require('request');
const _ = require('lodash');
const resultFile = process.argv[2];
const fileUrls = ['https://raw.githubusercontent.com/Metatavu/paatos/master/data/tehtavaluokat-espoo.txt', 'https://raw.githubusercontent.com/Metatavu/paatos/master/data/tehtavaluokat-oulu.txt'];
const result = {};
function requestFiles(urls) {
const requests = _.map(urls, (url) => {
return new Promise((resolve) => {
request(url, (error, response, body) => {
resolve(body);
});
});
});
return Promise.all(requests);
}
requestFiles(fileUrls).then((bodies) => {
let datas = bodies.join('\n');
const lines = datas.split('\n');
const lineDatas = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.match(/^([0-9]{2}\.{0,1}){1,}\ .*/)) {
const nameIndex = line.indexOf(' ');
const name = _.trim(line.substring(nameIndex + 1));
const id = line.substring(0, nameIndex);
lineDatas.push({
id: id.replace(/\./g, ' '),
name: _.capitalize(name.toLowerCase()),
level: _.sumBy(id, (char) => {
return char === '.' ? 1 : 0;
})
});
}
}
const sortedLines = _.sortBy(lineDatas, ['level', 'id']);
_.forEach(sortedLines, (lineData) => {
const idTree = lineData.id.split(' ');
if (idTree.length === 1) {
result[idTree[0]] = lineData;
} else {
const leftId = idTree.pop();
let parentNode = result[idTree[0]];
for (let i = 1; i < idTree.length; i++) {
parentNode = parentNode.children[idTree[i]];
}
if (parentNode) {
parentNode.children = (parentNode.children || {});
parentNode.children[leftId] = lineData;
}
}
});
fs.writeFileSync(resultFile, JSON.stringify(result, null, 2));
});
})();