All files / sportident/src/storage SiArray.ts

100% Statements 29/29
100% Branches 3/3
100% Functions 9/9
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 6026x 26x 26x       26x   132x 132x   132x       25x       4x 5x 1x   4x 4x         3x           278x 9078x 9078x 9078x 1487x   7591x   278x       30x 30x 30x 61x 61x 61x 60x     14x      
import _ from 'lodash';
import {ISiDataType, ISiStorageData, ValueFromStringError} from './interfaces';
import {SiDataType} from './SiDataType';
 
export type SiArrayValue<T> = (T|undefined)[];
 
export class SiArray<T> extends SiDataType<SiArrayValue<T>> implements ISiDataType<SiArrayValue<T>> {
    constructor(
                public length: number,
                public getDefinitionAtIndex: (index: number) => ISiDataType<T>,
    ) {
        super();
    }
 
    typeSpecificIsValueValid(_value: SiArrayValue<T>): boolean {
        return true;
    }
 
    typeSpecificValueToString(value: SiArrayValue<T>): string {
        return value.map((itemValue, index) => {
            if (itemValue === undefined) {
                return '?';
            }
            const definition = this.getDefinitionAtIndex(index);
            return definition.valueToString(itemValue);
        }).join(', ');
    }
 
    typeSpecificValueFromString(_string: string): ValueFromStringError {
        return new ValueFromStringError(
            `${this.constructor.name} does not support string parsing`,
        );
    }
 
    typeSpecificExtractFromData(data: ISiStorageData): SiArrayValue<T>|undefined {
        const arrayValue = _.range(this.length).map((index) => {
            const definition = this.getDefinitionAtIndex(index);
            const itemFieldValue = definition.extractFromData(data);
            if (itemFieldValue === undefined) {
                return undefined;
            }
            return itemFieldValue.value;
        });
        return arrayValue;
    }
 
    typeSpecificUpdateData(data: ISiStorageData, newValue: SiArrayValue<T>): ISiStorageData {
        const updateLength = Math.min(newValue.length, this.length);
        let tempData = data;
        _.range(updateLength).forEach((index) => {
            const definition = this.getDefinitionAtIndex(index);
            const newItemValue = newValue[index];
            if (newItemValue !== undefined) {
                tempData = definition.updateData(tempData, newItemValue);
            }
        });
        return tempData;
    }
}