import { injectable } from 'inversify'; import { IStorage } from '../interfaces/storages/IStorage'; import { initializable } from '../decorators/Initializable'; import { RandomGeneratorUtils } from '../utils/RandomGeneratorUtils'; @injectable() export abstract class MapStorage implements IStorage { /** * @type {string} */ @initializable() protected storageId: string; /** * @type {Map } */ @initializable() protected storage: Map ; /** * @param key * @returns {T} */ public get (key: string | number): T { const value: T | undefined = this.storage.get(key); if (!value) { throw new Error(`No value found in map storage with key \`${key}\``); } return value; } /** * @param value * @returns {string | number | null} */ public getKeyOf (value: T): string | number | null { for (const [key, storageValue] of this.storage) { if (value === storageValue) { return key; } } return null; } /** * @returns {number} */ public getLength (): number { return this.storage.size; } /** * @returns {Map } */ public getStorage (): Map { return this.storage; } /** * @returns {string} */ public getStorageId (): string { return this.storageId; } /** * @param args */ public initialize (...args: any[]): void { this.storage = new Map (); this.storageId = RandomGeneratorUtils.getRandomString(6); } /** * @param storage * @param mergeId */ public mergeWith (storage: this, mergeId: boolean = false): void { this.storage = new Map ([...this.storage, ...storage.getStorage()]); if (mergeId) { this.storageId = storage.getStorageId(); } } /** * @param key * @param value */ public set (key: string | number, value: T): void { this.storage.set(key, value); } }