SizeFormatHelpers.js 583 B

123456789101112131415161718192021222324252627
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Sean Larkin @thelarkinn
  4. */
  5. "use strict";
  6. /**
  7. * @param {number} size the size in bytes
  8. * @returns {string} the formatted size
  9. */
  10. exports.formatSize = size => {
  11. if (typeof size !== "number" || Number.isNaN(size) === true) {
  12. return "unknown size";
  13. }
  14. if (size <= 0) {
  15. return "0 bytes";
  16. }
  17. const abbreviations = ["bytes", "KiB", "MiB", "GiB"];
  18. const index = Math.floor(Math.log(size) / Math.log(1024));
  19. return `${+(size / Math.pow(1024, index)).toPrecision(3)} ${
  20. abbreviations[index]
  21. }`;
  22. };