set-array.umd.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.setArray = {}));
  5. })(this, (function (exports) { 'use strict';
  6. /**
  7. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  8. * index of the `key` in the backing array.
  9. *
  10. * This is designed to allow synchronizing a second array with the contents of the backing array,
  11. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  12. * and there are never duplicates.
  13. */
  14. class SetArray {
  15. constructor() {
  16. this._indexes = { __proto__: null };
  17. this.array = [];
  18. }
  19. }
  20. /**
  21. * Typescript doesn't allow friend access to private fields, so this just casts the set into a type
  22. * with public access modifiers.
  23. */
  24. function cast(set) {
  25. return set;
  26. }
  27. /**
  28. * Gets the index associated with `key` in the backing array, if it is already present.
  29. */
  30. function get(setarr, key) {
  31. return cast(setarr)._indexes[key];
  32. }
  33. /**
  34. * Puts `key` into the backing array, if it is not already present. Returns
  35. * the index of the `key` in the backing array.
  36. */
  37. function put(setarr, key) {
  38. // The key may or may not be present. If it is present, it's a number.
  39. const index = get(setarr, key);
  40. if (index !== undefined)
  41. return index;
  42. const { array, _indexes: indexes } = cast(setarr);
  43. const length = array.push(key);
  44. return (indexes[key] = length - 1);
  45. }
  46. /**
  47. * Pops the last added item out of the SetArray.
  48. */
  49. function pop(setarr) {
  50. const { array, _indexes: indexes } = cast(setarr);
  51. if (array.length === 0)
  52. return;
  53. const last = array.pop();
  54. indexes[last] = undefined;
  55. }
  56. /**
  57. * Removes the key, if it exists in the set.
  58. */
  59. function remove(setarr, key) {
  60. const index = get(setarr, key);
  61. if (index === undefined)
  62. return;
  63. const { array, _indexes: indexes } = cast(setarr);
  64. for (let i = index + 1; i < array.length; i++) {
  65. const k = array[i];
  66. array[i - 1] = k;
  67. indexes[k]--;
  68. }
  69. indexes[key] = undefined;
  70. array.pop();
  71. }
  72. exports.SetArray = SetArray;
  73. exports.get = get;
  74. exports.pop = pop;
  75. exports.put = put;
  76. exports.remove = remove;
  77. Object.defineProperty(exports, '__esModule', { value: true });
  78. }));
  79. //# sourceMappingURL=set-array.umd.js.map