-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextToJsonAdapter.js
72 lines (56 loc) · 1.3 KB
/
TextToJsonAdapter.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
"use strict";
/**
*
* @param {*} text
* @returns {JSON}
*/
module.exports = textToJsonAdapter;
const LANGUAGE_SEPARATOR = /\s%%\s/;
const LB_REGEX = /\n/gi;
const COLON_REGEX = /:\s|\s/gi;
var isRawDate = v => /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/.test(v);
var toCamelCase = (input) => {
return input
.toLowerCase()
.split("-")
.map((word, index) => {
if(!index) {
return word;
}
return word.charAt(0).toUpperCase() + word.substr(1);
})
.join('');
};
function textToJsonAdapter(text) {
let body = text
.split(LANGUAGE_SEPARATOR)
.map(i => {
let res = {};
i.split(LB_REGEX).forEach(j => {
let item = j.split(COLON_REGEX);
let key = toCamelCase(item.shift());
let value = item.pop();
if(isRawDate(value)) {
let date = value
.split('-')
.map((item, index) => {
item = Number(item);
switch(index) {
case 1:
--item;
break;
}
return item;
});
value = new Date(
Date.UTC(date[0], date[1], date[2])
);
}
res[key] = value;
});
return res;
})
;
let header = [body.shift()];
return {header, body};
}