prettierBytes.js 1003 B

12345678910111213141516171819202122232425262728293031
  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
  4. module.exports = function prettierBytes (num) {
  5. if (typeof num !== 'number' || isNaN(num)) {
  6. throw new TypeError('Expected a number, got ' + typeof num)
  7. }
  8. var neg = num < 0
  9. var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  10. if (neg) {
  11. num = -num
  12. }
  13. if (num < 1) {
  14. return (neg ? '-' : '') + num + ' B'
  15. }
  16. var exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1)
  17. num = Number(num / Math.pow(1024, exponent))
  18. var unit = units[exponent]
  19. if (num >= 10 || num % 1 === 0) {
  20. // Do not show decimals when the number is two-digit, or if the number has no
  21. // decimal component.
  22. return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit
  23. } else {
  24. return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit
  25. }
  26. }