-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
65 lines (55 loc) · 1.6 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
'use strict';
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/
var sizes = [
'Bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'
];
/**
Pretty print a size from bytes
@method pretty
@param {Number} size The number to pretty print
@param {Boolean} [nospace=false] Don't print a space
@param {Boolean} [one=false] Only print one character
@param {Number} [places=1] Number of decimal places to return
@param {Boolen} [numOnly] Return only the converted number and not size string
*/
module.exports = function (size, nospace, one, places, numOnly) {
if (typeof nospace === 'object') {
var opts = nospace;
nospace = opts.nospace;
one = opts.one;
places = opts.places || 1;
numOnly = opts.numOnly;
} else {
places = places || 1;
}
var mysize;
for (var id = 0; id < sizes.length; ++id) {
var unit = sizes[id];
if (one) {
unit = unit.slice(0, 1);
}
var s = Math.pow(1024, id);
var fixed;
if (size >= s) {
fixed = String((size / s).toFixed(places));
if (fixed.indexOf('.0') === fixed.length - 2) {
fixed = fixed.slice(0, -2);
}
mysize = fixed + (nospace ? '' : ' ') + unit;
}
}
// zero handling
// always prints in Bytes
if (!mysize) {
var _unit = (one ? sizes[0].slice(0, 1) : sizes[0]);
mysize = '0' + (nospace ? '' : ' ') + _unit;
}
if (numOnly) {
mysize = Number.parseFloat(mysize);
}
return mysize;
};