index.js 581 B

123456789101112131415161718192021222324
  1. 'use strict';
  2. const UNITS = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  3. module.exports = num => {
  4. if (!Number.isFinite(num)) {
  5. throw new TypeError(`Expected a finite number, got ${typeof num}: ${num}`);
  6. }
  7. const neg = num < 0;
  8. if (neg) {
  9. num = -num;
  10. }
  11. if (num < 1) {
  12. return (neg ? '-' : '') + num + ' B';
  13. }
  14. const exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), UNITS.length - 1);
  15. const numStr = Number((num / Math.pow(1000, exponent)).toPrecision(3));
  16. const unit = UNITS[exponent];
  17. return (neg ? '-' : '') + numStr + ' ' + unit;
  18. };