util.js 1.6 KB

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