-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (60 loc) · 1.81 KB
/
index.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
const stats = require('stats-lite');
const isnumber = require('isnumber');
function toArray(list) {
return Array.isArray(list) ? list : list.split(' ');
}
function Stat(fields, line) {
this.fields = toArray(fields);
this.values = {};
this.fields.forEach(field => {
this.values[field] = [];
});
this.line = line || '\n------------------------------\n';
}
Stat.prototype = {
add: function(item) {
this.fields.forEach(field => {
let value = item[field];
isnumber(value) &&
this.values[field].push(value);
});
return this;
},
field: function(fields) {
fields && (this._fields = toArray(fields));
return this;
},
result: function(methods) {
let output = [];
methods = toArray(methods);
let fields = this._fields ? this._fields : this.fields.slice(0);
fields.forEach(field => {
if (this.fields.indexOf(field) === -1) return; // field not support
output.push(this.line);
methods.forEach(method => {
if (!stats[method]) return; // method not support
output.push(`${field} ${method}: ${stats[method](this.values[field]).toFixed(2)}`);
});
});
delete this._fields;
return output.join('\n');
},
rank: function() {
let result = {};
let fields = this._fields ? this._fields : this.fields.slice(0);
fields.forEach(field => {
if (this.fields.indexOf(field) === -1) return; // field not support
result[field] = stats.sum(this.values[field]);
});
let keys = Object.keys(result);
let values = Object.values(result);
let output = [this.line, 'Rank: '];
values.slice(0).sort((x, y) => {
return y - x;
}).forEach((value, index) => {
output.push(`${index}. ${keys[values.indexOf(value)]} ${value}`);
});
return output.join('\n');
},
};
module.exports = Stat;