set-array.mjs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * Gets the index associated with `key` in the backing array, if it is already present.
  3. */
  4. let get;
  5. /**
  6. * Puts `key` into the backing array, if it is not already present. Returns
  7. * the index of the `key` in the backing array.
  8. */
  9. let put;
  10. /**
  11. * Pops the last added item out of the SetArray.
  12. */
  13. let pop;
  14. /**
  15. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  16. * index of the `key` in the backing array.
  17. *
  18. * This is designed to allow synchronizing a second array with the contents of the backing array,
  19. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  20. * and there are never duplicates.
  21. */
  22. class SetArray {
  23. constructor() {
  24. this._indexes = { __proto__: null };
  25. this.array = [];
  26. }
  27. }
  28. (() => {
  29. get = (strarr, key) => strarr._indexes[key];
  30. put = (strarr, key) => {
  31. // The key may or may not be present. If it is present, it's a number.
  32. const index = get(strarr, key);
  33. if (index !== undefined)
  34. return index;
  35. const { array, _indexes: indexes } = strarr;
  36. return (indexes[key] = array.push(key) - 1);
  37. };
  38. pop = (strarr) => {
  39. const { array, _indexes: indexes } = strarr;
  40. if (array.length === 0)
  41. return;
  42. const last = array.pop();
  43. indexes[last] = undefined;
  44. };
  45. })();
  46. export { SetArray, get, pop, put };
  47. //# sourceMappingURL=set-array.mjs.map