json.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.jsonSizeApprox = exports.jsonSize = void 0;
  4. const utf8_1 = require("../strings/utf8");
  5. const numberSize = (num) => {
  6. const isInteger = num === Math.round(num);
  7. if (isInteger)
  8. return Math.max(Math.floor(Math.log10(Math.abs(num))), 0) + 1 + (num < 0 ? 1 : 0);
  9. return JSON.stringify(num).length;
  10. };
  11. const stringSize = (str) => {
  12. const strLength = str.length;
  13. let byteLength = strLength;
  14. let pos = 0;
  15. while (pos < strLength) {
  16. const value = str.charCodeAt(pos++);
  17. if (value < 128) {
  18. switch (value) {
  19. case 8:
  20. case 9:
  21. case 10:
  22. case 12:
  23. case 13:
  24. case 34:
  25. case 92:
  26. byteLength += 1;
  27. break;
  28. }
  29. continue;
  30. }
  31. else
  32. return (0, utf8_1.utf8Size)(JSON.stringify(str));
  33. }
  34. return byteLength + 2;
  35. };
  36. const booleanSize = (bool) => (bool ? 4 : 5);
  37. const arraySize = (arr) => {
  38. let size = 0;
  39. const length = arr.length;
  40. for (let i = 0; i < length; i++)
  41. size += (0, exports.jsonSize)(arr[i]);
  42. return size + 2 + (length > 1 ? length - 1 : 0);
  43. };
  44. const objectSize = (obj) => {
  45. let size = 2;
  46. let length = 0;
  47. for (const key in obj)
  48. if (obj.hasOwnProperty(key)) {
  49. length++;
  50. size += stringSize(key) + (0, exports.jsonSize)(obj[key]);
  51. }
  52. const colonSize = length;
  53. const commaSize = length > 1 ? length - 1 : 0;
  54. return size + colonSize + commaSize;
  55. };
  56. const jsonSize = (value) => {
  57. if (value === null)
  58. return 4;
  59. switch (typeof value) {
  60. case 'number':
  61. return numberSize(value);
  62. case 'string':
  63. return stringSize(value);
  64. case 'boolean':
  65. return booleanSize(value);
  66. }
  67. if (value instanceof Array)
  68. return arraySize(value);
  69. return objectSize(value);
  70. };
  71. exports.jsonSize = jsonSize;
  72. const jsonSizeApprox = (value) => {
  73. if (value === null)
  74. return 4;
  75. switch (typeof value) {
  76. case 'number':
  77. return numberSize(value);
  78. case 'string':
  79. return value.length;
  80. case 'boolean':
  81. return booleanSize(value);
  82. }
  83. if (value instanceof Array)
  84. return arraySize(value);
  85. return objectSize(value);
  86. };
  87. exports.jsonSizeApprox = jsonSizeApprox;
  88. //# sourceMappingURL=json.js.map