Нема описа

set-array.ts 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Gets the index associated with `key` in the backing array, if it is already present.
  3. */
  4. export let get: (strarr: SetArray, key: string) => number | undefined;
  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. export let put: (strarr: SetArray, key: string) => number;
  10. /**
  11. * Pops the last added item out of the SetArray.
  12. */
  13. export let pop: (strarr: SetArray) => void;
  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. export class SetArray {
  23. private declare _indexes: { [key: string]: number | undefined };
  24. declare array: readonly string[];
  25. constructor() {
  26. this._indexes = { __proto__: null } as any;
  27. this.array = [];
  28. }
  29. static {
  30. get = (strarr, key) => strarr._indexes[key];
  31. put = (strarr, key) => {
  32. // The key may or may not be present. If it is present, it's a number.
  33. const index = get(strarr, key);
  34. if (index !== undefined) return index;
  35. const { array, _indexes: indexes } = strarr;
  36. return (indexes[key] = (array as string[]).push(key) - 1);
  37. };
  38. pop = (strarr) => {
  39. const { array, _indexes: indexes } = strarr;
  40. if (array.length === 0) return;
  41. const last = (array as string[]).pop()!;
  42. indexes[last] = undefined;
  43. };
  44. }
  45. }