forked from hakobera/nvmw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bytes.js
40 lines (35 loc) · 958 Bytes
/
bytes.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
/**
* Parse byte `size` string.
*
* @param {String} size
* @return {Number}
* @api public
*/
module.exports = function (size) {
if ('number' == typeof size) return convert(size);
var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb|tb)$/)
, n = parseFloat(parts[1])
, type = parts[2];
var map = {
kb: 1 << 10
, mb: 1 << 20
, gb: 1 << 30
, tb: ((1 << 30) * 1024)
};
return map[type] * n;
};
/**
* convert bytes into string.
*
* @param {Number} b - bytes to convert
* @return {String}
* @api public
*/
function convert (b) {
var tb = ((1 << 30) * 1024), gb = 1 << 30, mb = 1 << 20, kb = 1 << 10;
if (b >= tb) return (Math.round(b / tb * 100) / 100) + 'tb';
if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'gb';
if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'mb';
if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'kb';
return b + 'b';
}