-
Notifications
You must be signed in to change notification settings - Fork 27
/
helper.js
75 lines (71 loc) · 1.92 KB
/
helper.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
'use strict';
/**
* Helper
*/
module.exports = {
ucWords(string) {
return string.replace('/\w\S*/g', (str) => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase()); // eslint-disable-line no-useless-escape
},
formatNumber(x) {
return x.toLocaleString('en');
},
formatBytes(bytes, decimals) {
const b = parseInt(bytes, 10);
if (b === 0) {
return '0 Byte';
}
const k = 1024;
const dm = decimals + 1 || 3;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(b) / Math.log(k));
return `${(b / Math.pow(k, i)).toPrecision(dm)} ${sizes[i]}`; // eslint-disable-line no-restricted-properties
},
parseCommand(message) {
const tokens = message.split(' ');
if (!tokens[0].match(/^\//)) {
return null;
}
const command = [];
const cmd = tokens.shift();
const match = cmd.match(/\/(\w*)/);
if (match.length > 0) {
command[match[1]] = tokens;
}
return command;
},
getMessage(message) {
let m = '';
if (message) {
m = message.toString().trim();
} else {
m = '';
}
return (m.length > 0 ? m : 'N/A');
},
formatMessage(title, description, fields) {
let message = '';
if (title.length > 0) {
message = `<strong>${title}</strong>\n`;
}
if (description.length > 0) {
message += `<em>${description}</em>\n`;
}
if (fields.length > 0) {
message += `<pre>${this.parseFields(fields)}</pre>`;
}
return message;
},
parseFields(fields) {
const data = [];
fields.forEach((entry) => {
if (entry.title && entry.title.length > 0) {
data.push(`${entry.title}: ${entry.value}`);
}
});
return data.join("\n"); // eslint-disable-line quotes
},
validateIp(ip) {
const matcher = /^(?:(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)\.){3}(?:2[0-4]\d|25[0-5]|1\d{2}|[1-9]?\d)$/;
return matcher.test(ip);
},
};