map.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { iterableToArray } from '../util';
  7. // TODO: rename to "linear map" and just do key value mapping from index?
  8. /** Immutable by convention IntMap */
  9. interface IntMap<T> {
  10. has(key: number): boolean,
  11. keys(): IterableIterator<number>,
  12. values(): IterableIterator<T>,
  13. get(key: number): T,
  14. readonly size: number
  15. }
  16. namespace IntMap {
  17. export const Empty: IntMap<any> = new Map<number, any>();
  18. export interface Mutable<T> extends IntMap<T> {
  19. set(key: number, value: T): void;
  20. }
  21. export function keyArray<T>(map: IntMap<T>): number[] {
  22. return iterableToArray(map.keys());
  23. }
  24. export function Mutable<T>(): Mutable<T> {
  25. return new Map<number, T>() as Mutable<T>;
  26. }
  27. export function asImmutable<T>(map: IntMap<T>): IntMap<T> {
  28. return map;
  29. }
  30. export function copy<T>(map: IntMap<T>): Mutable<T> {
  31. const ret = Mutable<T>();
  32. const it = map.keys();
  33. while (true) {
  34. const { done, value } = it.next();
  35. if (done) break;
  36. ret.set(value, map.get(value));
  37. }
  38. return ret;
  39. }
  40. export function addFrom<T>(map: Mutable<T>, src: IntMap<T>) {
  41. const it = src.keys();
  42. while (true) {
  43. const { done, value } = it.next();
  44. if (done) break;
  45. map.set(value, src.get(value));
  46. }
  47. return map;
  48. }
  49. }
  50. export { IntMap };