Source: util/format_storage.es.js

  1. /**
  2. * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or modify it under
  5. * the terms of the GNU Lesser General Public License as published by the Free
  6. * Software Foundation; either version 2.1 of the License, or (at your option)
  7. * any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  12. * details.
  13. */
  14. const DEFAULT_OPTIONS = {
  15. addSpaceBeforeSuffix: false,
  16. decimalSeparator: '.',
  17. denominator: 1024.0,
  18. suffixGB: 'GB',
  19. suffixKB: 'KB',
  20. suffixMB: 'MB',
  21. };
  22. /**
  23. * Returns storage number formatted as a String
  24. * @param {!Number} size Storage size to be formatted
  25. * @param {Object} options Object representing optional parameters for
  26. * formatting storage size
  27. * @return {String} formattedStorage Final formatted storage outputted as a String
  28. * @review
  29. */
  30. export default function formatStorage(size, options = {}) {
  31. const {
  32. addSpaceBeforeSuffix,
  33. decimalSeparator,
  34. denominator,
  35. suffixGB,
  36. suffixKB,
  37. suffixMB,
  38. } = {
  39. ...DEFAULT_OPTIONS,
  40. ...options,
  41. };
  42. if (typeof size !== 'number') {
  43. throw new TypeError('Parameter size must be a number');
  44. }
  45. let decimalPlaces = 0;
  46. let suffix = suffixKB;
  47. size /= denominator;
  48. if (size >= denominator) {
  49. suffix = suffixMB;
  50. size /= denominator;
  51. decimalPlaces = 1;
  52. }
  53. if (size >= denominator) {
  54. suffix = suffixGB;
  55. size /= denominator;
  56. decimalPlaces = 1;
  57. }
  58. let fixedSize = size.toFixed(decimalPlaces);
  59. if (decimalSeparator !== '.') {
  60. fixedSize = fixedSize.replace(/\./, decimalSeparator);
  61. }
  62. return fixedSize + (addSpaceBeforeSuffix ? ' ' : '') + suffix;
  63. }