All files / sportident/src/storage SiDict.ts

100% Statements 29/29
100% Branches 2/2
100% Functions 11/11
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 6526x 26x         26x   2307x   2307x       20x 41x         3x 6x 6x 6x 1x     5x 5x         3x           2315x 2315x 4721x 4721x 4721x 2080x   2641x   2315x       14x 14x 24x 24x   7x       2352x      
import {ISiDataType, ISiStorageData, ValueFromStringError} from './interfaces';
import {SiDataType} from './SiDataType';
 
export type SiDictValue<T> = {[key in keyof T]: T[key]|undefined};
export type SiPartialDictValue<T> = {[key in keyof T]?: T[key]};
 
export class SiDict<T> extends SiDataType<SiDictValue<T>> implements ISiDataType<SiDictValue<T>> {
    constructor(
                public readonly definitionDict: {[key in keyof T]: ISiDataType<T[key]>},
    ) {
        super();
    }
 
    typeSpecificIsValueValid(value: SiDictValue<T>): boolean {
        return this.keysOfT.every((key) => (
            value[key] !== undefined
        ));
    }
 
    typeSpecificValueToString(value: SiDictValue<T>): string {
        return this.keysOfT.map((key) => {
            const definition = this.definitionDict[key];
            const itemValue = value[key];
            if (itemValue === undefined) {
                return `${String(key)}: ?`;
            }
            // @ts-ignore
            const itemValueString = definition.valueToString(itemValue);
            return `${String(key)}: ${itemValueString}`;
        }).join(', ');
    }
 
    typeSpecificValueFromString(_string: string): ValueFromStringError {
        return new ValueFromStringError(
            `${this.constructor.name} does not support string parsing`,
        );
    }
 
    typeSpecificExtractFromData(data: ISiStorageData): SiDictValue<T> {
        const dictValue: SiPartialDictValue<T> = {};
        this.keysOfT.forEach((key) => {
            const definition = this.definitionDict[key];
            const itemFieldValue = definition.extractFromData(data);
            if (itemFieldValue === undefined) {
                return;
            }
            dictValue[key] = itemFieldValue.value;
        });
        return dictValue as SiDictValue<T>;
    }
 
    typeSpecificUpdateData(data: ISiStorageData, newValue: SiDictValue<T>): ISiStorageData {
        let tempData = data;
        this.keysOfT.forEach((key) => {
            const definition = this.definitionDict[key];
            tempData = definition.updateData(tempData, newValue[key]!);
        });
        return tempData;
    }
 
    get keysOfT(): (keyof T)[] {
        return Object.keys(this.definitionDict) as (keyof T)[];
    }
}