MapStorage.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { injectable } from 'inversify';
  2. import { IStorage } from '../interfaces/storages/IStorage';
  3. import { initializable } from '../decorators/Initializable';
  4. import { RandomGeneratorUtils } from '../utils/RandomGeneratorUtils';
  5. @injectable()
  6. export abstract class MapStorage <T> implements IStorage <T> {
  7. /**
  8. * @type {string}
  9. */
  10. @initializable()
  11. protected storageId: string;
  12. /**
  13. * @type {Map <string | number, T>}
  14. */
  15. @initializable()
  16. protected storage: Map <string | number, T>;
  17. /**
  18. * @param key
  19. * @returns {T}
  20. */
  21. public get (key: string | number): T {
  22. const value: T | undefined = this.storage.get(key);
  23. if (!value) {
  24. throw new Error(`No value found in map storage with key \`${key}\``);
  25. }
  26. return value;
  27. }
  28. /**
  29. * @param value
  30. * @returns {string | number | null}
  31. */
  32. public getKeyOf (value: T): string | number | null {
  33. for (const [key, storageValue] of this.storage) {
  34. if (value === storageValue) {
  35. return key;
  36. }
  37. }
  38. return null;
  39. }
  40. /**
  41. * @returns {number}
  42. */
  43. public getLength (): number {
  44. return this.storage.size;
  45. }
  46. /**
  47. * @returns {Map <string | number, T>}
  48. */
  49. public getStorage (): Map <string | number, T> {
  50. return this.storage;
  51. }
  52. /**
  53. * @returns {string}
  54. */
  55. public getStorageId (): string {
  56. return this.storageId;
  57. }
  58. /**
  59. * @param args
  60. */
  61. public initialize (...args: any[]): void {
  62. this.storage = new Map <string | number, T> ();
  63. this.storageId = RandomGeneratorUtils.getRandomString(6);
  64. }
  65. /**
  66. * @param storage
  67. * @param mergeId
  68. */
  69. public mergeWith (storage: this, mergeId: boolean = false): void {
  70. this.storage = new Map <string | number, T> ([...this.storage, ...storage.getStorage()]);
  71. if (mergeId) {
  72. this.storageId = storage.getStorageId();
  73. }
  74. }
  75. /**
  76. * @param key
  77. * @param value
  78. */
  79. public set (key: string | number, value: T): void {
  80. this.storage.set(key, value);
  81. }
  82. }