MapStorage.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { IStorage } from '../interfaces/IStorage';
  2. import { Utils } from '../Utils';
  3. export abstract class MapStorage <T> implements IStorage <T> {
  4. /**
  5. * @type {Map <string | number, T>}
  6. */
  7. protected storage: Map <string | number, T> = new Map <string | number, T> ();
  8. /**
  9. * @param key
  10. * @returns {T}
  11. */
  12. public get (key: string | number): T {
  13. const value: T | undefined = this.storage.get(key);
  14. if (!value) {
  15. throw new Error(`No value found in map storage with key \`${key}\``);
  16. }
  17. return value;
  18. }
  19. /**
  20. * @param value
  21. * @returns {string | number | null}
  22. */
  23. public getKeyOf (value: T): string | number | null {
  24. return Utils.mapGetFirstKeyOf(this.storage, value);
  25. }
  26. /**
  27. * @returns {number}
  28. */
  29. public getLength (): number {
  30. return Array.from(this.storage).length;
  31. }
  32. /**
  33. * @returns {Map <string | number, T>}
  34. */
  35. public getStorage (): Map <string | number, T> {
  36. return this.storage;
  37. }
  38. /**
  39. * @param key
  40. * @param value
  41. */
  42. public set (key: string | number, value: T): void {
  43. this.storage.set(key, value);
  44. }
  45. }