All files / sportident/src/storage SiEnum.ts

100% Statements 24/24
100% Branches 2/2
100% Functions 9/9
100% Lines 23/23

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  26x 26x 26x 26x   26x         27x 69x   27x 27x       56x   69x         46x       16x       9x 5x       4x       56x 56x 56x 56x 56x       22x 22x      
import _ from 'lodash';
import * as utils from '../utils';
import {ISiDataType, ISiStorageData, ValueFromStringError} from './interfaces';
import {SiDataType} from './SiDataType';
import {SiInt, SiIntegerPartDefinition} from './SiInt';
 
export class SiEnum<T extends {[key: string]: number}> extends SiDataType<keyof T> implements ISiDataType<keyof T> {
    private intField: SiInt;
 
    constructor(
        parts: SiIntegerPartDefinition[],
                public readonly dict: T,
                public readonly getIntValue = (value: unknown): number|undefined => value as number,
    ) {
        super();
        this.intField = new SiInt(parts);
    }
 
    getLookupDict(): {[key: string]: string} {
        return utils.getLookup(
            this.dict,
            (value) => `${this.getIntValue(value)}`,
        );
    }
 
    typeSpecificIsValueValid(value: keyof T): boolean {
        return this.dict[value] !== undefined;
    }
 
    typeSpecificValueToString(value: keyof T): string {
        return String(value);
    }
 
    typeSpecificValueFromString(string: string): keyof T|ValueFromStringError {
        if (this.dict[string] === undefined) {
            return new ValueFromStringError(
                `Value for ${this.constructor.name} must be an enum option, not "${string}"`,
            );
        }
        return string as keyof T;
    }
 
    typeSpecificExtractFromData(data: ISiStorageData): keyof T|undefined {
        const intValue = this.intField.typeSpecificExtractFromData(data);
        const intString = `${intValue}`;
        const lookupDict = this.getLookupDict();
        const key = lookupDict[intString];
        return key;
    }
 
    typeSpecificUpdateData(data: ISiStorageData, newValue: keyof T): ISiStorageData {
        const newIntValue = this.dict[newValue];
        return this.intField.typeSpecificUpdateData(data, newIntValue);
    }
}