stringToBytes.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. /**
  7. * Copyright (c) Meta Platforms, Inc. and affiliates.
  8. *
  9. * This source code is licensed under the MIT license found in the
  10. * LICENSE file in the root directory of this source tree.
  11. */
  12. /**
  13. * Converts a string representing an amount of memory to bytes.
  14. *
  15. * @param input The value to convert to bytes.
  16. * @param percentageReference The reference value to use when a '%' value is supplied.
  17. */
  18. function stringToBytes(input, percentageReference) {
  19. if (input === null || input === undefined) {
  20. return input;
  21. }
  22. if (typeof input === 'string') {
  23. if (isNaN(Number.parseFloat(input.slice(-1)))) {
  24. // eslint-disable-next-line prefer-const
  25. let [, numericString, trailingChars] =
  26. input.match(/(.*?)([^0-9.-]+)$/i) || [];
  27. if (trailingChars && numericString) {
  28. const numericValue = Number.parseFloat(numericString);
  29. trailingChars = trailingChars.toLowerCase();
  30. switch (trailingChars) {
  31. case '%':
  32. input = numericValue / 100;
  33. break;
  34. case 'kb':
  35. case 'k':
  36. return numericValue * 1000;
  37. case 'kib':
  38. return numericValue * 1024;
  39. case 'mb':
  40. case 'm':
  41. return numericValue * 1000 * 1000;
  42. case 'mib':
  43. return numericValue * 1024 * 1024;
  44. case 'gb':
  45. case 'g':
  46. return numericValue * 1000 * 1000 * 1000;
  47. case 'gib':
  48. return numericValue * 1024 * 1024 * 1024;
  49. }
  50. }
  51. // It ends in some kind of char so we need to do some parsing
  52. } else {
  53. input = Number.parseFloat(input);
  54. }
  55. }
  56. if (typeof input === 'number') {
  57. if (input <= 1 && input > 0) {
  58. if (percentageReference) {
  59. return Math.floor(input * percentageReference);
  60. } else {
  61. throw new Error(
  62. 'For a percentage based memory limit a percentageReference must be supplied'
  63. );
  64. }
  65. } else if (input > 1) {
  66. return Math.floor(input);
  67. } else {
  68. throw new Error('Unexpected numerical input');
  69. }
  70. }
  71. throw new Error('Unexpected input');
  72. }
  73. // https://github.com/import-js/eslint-plugin-import/issues/1590
  74. var _default = stringToBytes;
  75. exports.default = _default;