-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
122 lines (100 loc) · 2.06 KB
/
utils.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const fs = require("fs");
const http = require("http");
const cutBefore = (src, cut) => {
if (!src) {
return null;
}
const i = src.indexOf(cut);
if (i < 0) {
return src;
}
const fi = i + cut.length;
return src.substr(fi);
}
const cutAfter = (src, cut) => {
if (!src) {
return null;
}
const i = src.indexOf(cut);
if (i < 0) {
return src;
}
return src.substr(0, i);
}
const cutMeta = (src) => {
if (!src) {
return null;
}
return src
.replace(/\[\/?[a-zA-Z]*\]/g, "")
.replace(/<br\/?>/g, "")
.replace(/\\u003cbr\/?\\u003e/g, "")
.replace(/{OakPC_ActionSkill}/g, "\"F\"")
.replace(/{OakPC_Melee}/g, "\"V\"")
.replace(/{OakPC_Grenade}/g, "\"G\"");
}
const get = (url, fn) => {
http.get(url, res => {
let data = "";
res.on("data", chunk => {
data += chunk;
});
res.on("end", () => {
const obj = JSON.parse(data);
fn && fn(obj);
});
}).on("error", err => {
console.log("Error during GET: " + err.message);
fn && fn(null);
});
}
const readFile = (file, fn) => {
fs.readFile(file, (err, data) => {
if (err) {
fn && fn(null);
}
else {
const obj = JSON.parse(data);
fn && fn(obj);
}
});
}
const writeFile = (file, obj, fn) => {
fs.writeFile(file, JSON.stringify(obj), "utf8", (err) => {
if (err) {
console.log(`Error writing to ${file}. Message: ${err.message}`);
}
fn && fn(err);
});
}
const findTop = (coll, getProp, getAgg) => {
const props = {};
for (const item of coll) {
const prop = getProp(item);
props[prop] = props[prop] || 0;
props[prop] += getAgg(item);
}
let topScore = 0;
let topProp = null;
for (const prop of Object.keys(props)) {
const score = props[prop];
if (score > topScore) {
topScore = score;
topProp = prop;
}
}
return [topProp, topScore];
}
const roundToTwo = (num) => {
return +(Math.round(num + "e+2") + "e-2");
}
module.exports = {
cutBefore,
cutAfter,
cutMeta,
get,
readFile,
writeFile,
findTop,
roundToTwo
};