All files / src/storages ArrayStorage.ts

96.3% Statements 26/27
83.33% Branches 10/12
100% Functions 1/1
96.15% Lines 25/26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 1071x       1x   1x     1x         1x           1x         6276x             3x   3x 1x     2x               3x   3x             16558x             3x             11027x             6275x 6275x             1x 1x   1x                   10303x 10302x   1x     10302x      
import { injectable } from 'inversify';
 
import { IStorage } from '../interfaces/storages/IStorage';
 
import { initializable } from '../decorators/Initializable';
 
import { RandomGeneratorUtils } from '../utils/RandomGeneratorUtils';
 
@injectable()
export abstract class ArrayStorage <T> implements IStorage <T> {
    /**
     * @type {T[]}
     */
    @initializable()
    protected storage: T[];
 
    /**
     * @type {string}
     */
    @initializable()
    protected storageId: string;
 
    /**
     * @type {number}
     */
    private storageLength: number = 0;
 
    /**
     * @param key
     * @returns {T}
     */
    public get (key: number): T {
        const value: T | undefined = this.storage[key];
 
        if (!value) {
            throw new Error(`No value found in array storage with key \`${key}\``);
        }
 
        return value;
    }
 
    /**
     * @param value
     * @returns {number | null}
     */
    public getKeyOf (value: T): number | null {
        const key: number = this.storage.indexOf(value);
 
        return key >= 0 ? key : null;
    }
 
    /**
     * @returns {number}
     */
    public getLength (): number {
        return this.storageLength;
    }
 
    /**
     * @returns {T[]}
     */
    public getStorage (): T[] {
        return this.storage;
    }
 
    /**
     * @returns {string}
     */
    public getStorageId (): string {
        return this.storageId;
    }
 
    /**
     * @param args
     */
    public initialize (...args: any[]): void {
        this.storage = [];
        this.storageId = RandomGeneratorUtils.getRandomString(6);
    }
 
    /**
     * @param storage
     * @param mergeId
     */
    public mergeWith (storage: this, mergeId: boolean = false): void {
        this.storage = [...this.storage, ...storage.getStorage()];
 
        Iif (mergeId) {
            this.storageId = storage.getStorageId();
        }
    }
 
    /**
     * @param key
     * @param value
     */
    public set (key: number, value: T): void {
        if (key === this.storageLength) {
            this.storage.push(value);
        } else {
            this.storage.splice(key, 0, value);
        }
 
        this.storageLength++;
    }
}