UNPKG

1 kBJavaScriptView Raw
1// Adapted from https://github.com/Flet/prettier-bytes/
2// Changing 1000 bytes to 1024, so we can keep uppercase KB vs kB
3// ISC License (c) Dan Flettre https://github.com/Flet/prettier-bytes/blob/master/LICENSE
4module.exports = function prettierBytes (num) {
5 if (typeof num !== 'number' || isNaN(num)) {
6 throw new TypeError('Expected a number, got ' + typeof num)
7 }
8
9 var neg = num < 0
10 var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
11
12 if (neg) {
13 num = -num
14 }
15
16 if (num < 1) {
17 return (neg ? '-' : '') + num + ' B'
18 }
19
20 var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1)
21 num = Number(num / Math.pow(1024, exponent))
22 var unit = units[exponent]
23
24 if (num >= 10 || num % 1 === 0) {
25 // Do not show decimals when the number is two-digit, or if the number has no
26 // decimal component.
27 return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit
28 } else {
29 return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit
30 }
31}