-
Notifications
You must be signed in to change notification settings - Fork 4
/
humanizer.js
104 lines (93 loc) 路 2.14 KB
/
humanizer.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
const humanizeDuration = require('humanize-duration');
const prettyBytes = require('pretty-bytes');
// Create a custom instance humanizer
// See: https://github.com/EvanHahn/HumanizeDuration.js#humanizers
const prettyDuration = humanizeDuration.humanizer({
delimiter: ' ',
spacer: '',
largest: 2,
round: true,
language: 'shortEn',
units: ['mo', 'w', 'd', 'h', 'm', 's'],
languages: {
shortEn: {
y() {
return 'y';
},
mo() {
return 'mo';
},
w() {
return 'w';
},
d() {
return 'd';
},
h() {
return 'h';
},
m() {
return 'm';
},
s() {
return 's';
},
ms() {
return 'ms';
},
decimal: '.'
}
}
});
/**
* Round the given value to the nearest 10
*
* @param {Number} value
* @return {Number}
*/
function round(value) {
return Math.round(value * 100) / 100;
}
/**
* Convert the given value into a human-readable duration
*
* @param {Number} value
* @return {String}
*/
function duration(value) {
value = value * 1000;
// Assume 1 second for values less than 1 second
if (value > 0 && value < 1000) {
value = 1000;
}
return prettyDuration(value);
}
/**
* Run the given humanizer with a value if the value is valid,
* otherwise return the value unchanged.
*
* @param {Number} value
* @param {Function} humanizer
* @param {String} append
* @return {Number|String}
*/
function runHumanizer(value, humanizer, append = '') {
if (typeof value !== 'number') {
return value;
}
return humanizer(value) + append;
}
module.exports = {
bytes(value) {
return runHumanizer(value, prettyBytes);
},
speed(value) {
return runHumanizer(value, prettyBytes, '/s');
},
duration(value) {
return runHumanizer(value, duration);
},
percentage(value) {
return runHumanizer(value, round, '%');
}
};