-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
76 lines (66 loc) · 2.18 KB
/
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
const defaultFields = ['name', 'pid', 'sessionName', 'sessionNumber', 'memUsage'];
const modulesFields = ['name', 'pid', 'modules'];
const servicesFields = ['name', 'pid', 'services'];
const appsFields = ['name', 'pid', 'memUsage', 'packageName'];
const verboseFields = [...defaultFields, 'status', 'username', 'cpuTime', 'windowTitle'];
const appsVerboseFields = [...verboseFields, 'packageName'];
const types = {
name: 'string',
pid: 'number',
sessioName: 'string',
sessionNumber: 'number',
memUsage: 'memory',
modules: 'array',
services: 'array',
packageName: 'string',
status: 'string',
username: 'string',
cpuTime: 'time',
windowTitle: 'string'
};
const toSeconds = string => {
const [h, m, s] = string.split(':');
return 3600 * h + 60 * m + Number(s);
};
class Parser {
constructor (options = {}) {
if (options.modules) {
this.fields = modulesFields;
} else if (options.services) {
this.fields = servicesFields;
} else if (options.apps) {
if (options.verbose) {
this.fields = appsVerboseFields;
} else {
this.fields = appsFields;
}
} else if (options.verbose) {
this.fields = verboseFields;
} else {
this.fields = defaultFields;
}
}
parse(string) {
return string.slice(1, -1).split('","').reduce((obj, value, index) => {
const field = this.fields[index];
switch (types[field]) {
case 'number':
obj[field] = Number(value);
break;
case 'array':
obj[field] = value.split(',');
break;
case 'memory':
obj[field] = value.replace(/\D/g, '') * 1024;
break;
case 'time':
obj[field] = toSeconds(value);
break;
default:
obj[field] = value;
}
return obj;
}, {});
}
}
module.exports = Parser;