pretty-bytes.js 983 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /*!
  2. pretty-bytes
  3. Convert bytes to a human readable string: 1337 → 1.34 kB
  4. https://github.com/sindresorhus/pretty-bytes
  5. by Sindre Sorhus
  6. MIT License
  7. */
  8. (function () {
  9. 'use strict';
  10. // Number.isNaN() polyfill
  11. var isNaN = function (val) {
  12. return val !== val;
  13. };
  14. var prettyBytes = function (num) {
  15. if (typeof num !== 'number' || isNaN(num)) {
  16. throw new TypeError('Expected a number');
  17. }
  18. var exponent;
  19. var unit;
  20. var neg = num < 0;
  21. var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  22. if (neg) {
  23. num = -num;
  24. }
  25. if (num < 1) {
  26. return (neg ? '-' : '') + num + ' B';
  27. }
  28. exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1);
  29. num = (num / Math.pow(1000, exponent)).toFixed(2) * 1;
  30. unit = units[exponent];
  31. return (neg ? '-' : '') + num + ' ' + unit;
  32. };
  33. if (typeof module !== 'undefined' && module.exports) {
  34. module.exports = prettyBytes;
  35. } else {
  36. self.prettyBytes = prettyBytes;
  37. }
  38. })();