3a7859dde1501a5a0fe3f87c2547e35ae905f8d7eb16f16e864cd3bf97b39d37d9e6d34b896bbe310e297a87219bb5eb281b19f483d542a38ee253f8c5c7c1 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /**
  2. * A collection of shims that provide minimal functionality of the ES6 collections.
  3. *
  4. * These implementations are not meant to be used outside of the ResizeObserver
  5. * modules as they cover only a limited range of use cases.
  6. */
  7. /* eslint-disable require-jsdoc, valid-jsdoc */
  8. const MapShim = (() => {
  9. if (typeof Map !== 'undefined') {
  10. return Map;
  11. }
  12. /**
  13. * Returns index in provided array that matches the specified key.
  14. *
  15. * @param {Array<Array>} arr
  16. * @param {*} key
  17. * @returns {number}
  18. */
  19. function getIndex(arr, key) {
  20. let result = -1;
  21. arr.some((entry, index) => {
  22. if (entry[0] === key) {
  23. result = index;
  24. return true;
  25. }
  26. return false;
  27. });
  28. return result;
  29. }
  30. return class {
  31. constructor() {
  32. this.__entries__ = [];
  33. }
  34. /**
  35. * @returns {boolean}
  36. */
  37. get size() {
  38. return this.__entries__.length;
  39. }
  40. /**
  41. * @param {*} key
  42. * @returns {*}
  43. */
  44. get(key) {
  45. const index = getIndex(this.__entries__, key);
  46. const entry = this.__entries__[index];
  47. return entry && entry[1];
  48. }
  49. /**
  50. * @param {*} key
  51. * @param {*} value
  52. * @returns {void}
  53. */
  54. set(key, value) {
  55. const index = getIndex(this.__entries__, key);
  56. if (~index) {
  57. this.__entries__[index][1] = value;
  58. } else {
  59. this.__entries__.push([key, value]);
  60. }
  61. }
  62. /**
  63. * @param {*} key
  64. * @returns {void}
  65. */
  66. delete(key) {
  67. const entries = this.__entries__;
  68. const index = getIndex(entries, key);
  69. if (~index) {
  70. entries.splice(index, 1);
  71. }
  72. }
  73. /**
  74. * @param {*} key
  75. * @returns {void}
  76. */
  77. has(key) {
  78. return !!~getIndex(this.__entries__, key);
  79. }
  80. /**
  81. * @returns {void}
  82. */
  83. clear() {
  84. this.__entries__.splice(0);
  85. }
  86. /**
  87. * @param {Function} callback
  88. * @param {*} [ctx=null]
  89. * @returns {void}
  90. */
  91. forEach(callback, ctx = null) {
  92. for (const entry of this.__entries__) {
  93. callback.call(ctx, entry[1], entry[0]);
  94. }
  95. }
  96. };
  97. })();
  98. export {MapShim as Map};