import _ from 'lodash'; import {ISiDataType, ISiStorageData, ValueFromStringError} from './interfaces'; import {SiDataType} from './SiDataType'; export type SiArrayValue = (T|undefined)[]; export class SiArray extends SiDataType> implements ISiDataType> { constructor( public length: number, public getDefinitionAtIndex: (index: number) => ISiDataType, ) { super(); } typeSpecificIsValueValid(_value: SiArrayValue): boolean { return true; } typeSpecificValueToString(value: SiArrayValue): 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|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): 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; } }