-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (60 loc) · 1.49 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
'use strict';
var fs = require('fs');
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function parseString(string) {
var quotes = ['\'', '"'];
if (quotes.indexOf(string.charAt(0)) !== -1 &&
quotes.indexOf(string.charAt(string.length - 1)) !== -1) {
return string.slice(1, string.length - 1);
}
return string;
}
function parseValue(value) {
return isNumber(value) ? Number(value) : parseString(value);
}
function parseValues(values) {
if (values.length === 1) {
return parseValue(values[0]);
}
return values.map(function(value) {
return parseValue(value);
});
}
function parse(text) {
var codex = {};
var uncommentedText = text.replace(/\([^\)]*\)/g, '');
var newlineNormalizedText = uncommentedText.replace(/\r\n/g, '\n').
replace(/[\s]*\n\n[\s]*/g, '\n\n');
var pairs = newlineNormalizedText.split('\n\n');
pairs.forEach(function(pair) {
if (!pair) {
return;
}
var values = pair.split('\n').map(function(string) {
return string.trim();
});
var key = values.shift();
if (key.indexOf('.') !== -1) {
var keys = key.split('.');
if (!codex[keys[0]]) {
codex[keys[0]] = {};
}
codex[keys[0]][keys[1]] = parseValues(values);
} else {
codex[key] = parseValues(values);
}
});
return codex;
}
function read(path) {
var text = fs.readFileSync(path, {
encoding: 'utf-8'
});
return parse(text);
}
module.exports = {
read: read,
parse: parse
};