ArrayStorage.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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 ArrayStorage <T> implements IStorage <T> {
  7. /**
  8. * @type {T[]}
  9. */
  10. @initializable()
  11. protected storage: T[];
  12. /**
  13. * @type {string}
  14. */
  15. @initializable()
  16. protected storageId: string;
  17. /**
  18. * @type {number}
  19. */
  20. private storageLength: number = 0;
  21. /**
  22. * @param key
  23. * @returns {T}
  24. */
  25. public get (key: number): T {
  26. const value: T | undefined = this.storage[key];
  27. if (!value) {
  28. throw new Error(`No value found in array storage with key \`${key}\``);
  29. }
  30. return value;
  31. }
  32. /**
  33. * @param value
  34. * @returns {number | null}
  35. */
  36. public getKeyOf (value: T): number | null {
  37. const key: number = this.storage.indexOf(value);
  38. return key >= 0 ? key : null;
  39. }
  40. /**
  41. * @returns {number}
  42. */
  43. public getLength (): number {
  44. return this.storageLength;
  45. }
  46. /**
  47. * @returns {T[]}
  48. */
  49. public getStorage (): 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 = [];
  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 = [...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: number, value: T): void {
  80. if (key === this.storageLength) {
  81. this.storage.push(value);
  82. } else {
  83. this.storage.splice(key, 0, value);
  84. }
  85. this.storageLength++;
  86. }
  87. }