util.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.byteLength = exports.installTimerFunctions = exports.pick = void 0;
  4. const globalThis_js_1 = require("./globalThis.js");
  5. function pick(obj, ...attr) {
  6. return attr.reduce((acc, k) => {
  7. if (obj.hasOwnProperty(k)) {
  8. acc[k] = obj[k];
  9. }
  10. return acc;
  11. }, {});
  12. }
  13. exports.pick = pick;
  14. // Keep a reference to the real timeout functions so they can be used when overridden
  15. const NATIVE_SET_TIMEOUT = globalThis_js_1.globalThisShim.setTimeout;
  16. const NATIVE_CLEAR_TIMEOUT = globalThis_js_1.globalThisShim.clearTimeout;
  17. function installTimerFunctions(obj, opts) {
  18. if (opts.useNativeTimers) {
  19. obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThis_js_1.globalThisShim);
  20. obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThis_js_1.globalThisShim);
  21. }
  22. else {
  23. obj.setTimeoutFn = globalThis_js_1.globalThisShim.setTimeout.bind(globalThis_js_1.globalThisShim);
  24. obj.clearTimeoutFn = globalThis_js_1.globalThisShim.clearTimeout.bind(globalThis_js_1.globalThisShim);
  25. }
  26. }
  27. exports.installTimerFunctions = installTimerFunctions;
  28. // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64)
  29. const BASE64_OVERHEAD = 1.33;
  30. // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9
  31. function byteLength(obj) {
  32. if (typeof obj === "string") {
  33. return utf8Length(obj);
  34. }
  35. // arraybuffer or blob
  36. return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
  37. }
  38. exports.byteLength = byteLength;
  39. function utf8Length(str) {
  40. let c = 0, length = 0;
  41. for (let i = 0, l = str.length; i < l; i++) {
  42. c = str.charCodeAt(i);
  43. if (c < 0x80) {
  44. length += 1;
  45. }
  46. else if (c < 0x800) {
  47. length += 2;
  48. }
  49. else if (c < 0xd800 || c >= 0xe000) {
  50. length += 3;
  51. }
  52. else {
  53. i++;
  54. length += 4;
  55. }
  56. }
  57. return length;
  58. }