-
Notifications
You must be signed in to change notification settings - Fork 0
/
usage-metrics-node.js
81 lines (65 loc) · 1.98 KB
/
usage-metrics-node.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
process.stdin.resume();
process.stdin.setEncoding("ascii");
let data = "";
// process each set of host info
function processInfoSet(infoSet) {
const output = [];
for (let set in infoSet) {
let outputString =
set + ': Average: ' + infoSet[set]['avg'] + ' Max: ' + infoSet[set]['max'] + ' Min: ' + infoSet[set]['min'];
output.push(outputString);
}
return output;
}
// get & process each line from input
function processLines(input) {
const averages = {};
const lines = input.split('\n');
const hostInfoSet = {};
for (let line of lines) {
// TODO: validate line input (for real)
if (line !== '') {
let host = line.split('|');
let hostName = host[0];
let hostPercentStrings = host[1].split(',');
hostInfoSet[hostName] = processPercents(hostPercentStrings);
}
}
return hostInfoSet;
}
// identify min, max, and avg from one set of percentages
function processPercents(percentStrings) {
const allPercentages = [];
const keyPercentages = {};
for (let percent of percentStrings) {
// TODO: validate value input
let floatValue = parseFloat(percent);
allPercentages.push(floatValue);
}
const length = allPercentages.length;
const lastIndex = length - 1;
const sum = allPercentages.reduce((accumulator, currentVal) =>
accumulator + currentVal);
const minPercent = allPercentages.sort(sortFloat)[0];
const maxPercent = allPercentages.sort(sortFloat)[lastIndex];
const average = sum / length;
keyPercentages['min'] = minPercent;
keyPercentages['max'] = maxPercent;
keyPercentages['avg'] = average;
return keyPercentages;
}
// create compareFunction for .sort()
function sortFloat(a, b) {
return a - b;
}
// READ INPUT
process.stdin.on("data", function (chunk) {
data += chunk;
});
// WRITE OUTPUT
process.stdin.on("end", function () {
const processedLines = processLines(data);
const output = processInfoSet(processedLines);
process.stdout.write(output.join("\n"));
process.stdout.write("\n")
});