import {ISiDataType, ISiStorageData, ValueFromStringError} from './interfaces'; import {SiDataType} from './SiDataType'; export type SiDictValue = {[key in keyof T]: T[key]|undefined}; export type SiPartialDictValue = {[key in keyof T]?: T[key]}; export class SiDict extends SiDataType> implements ISiDataType> { constructor( public readonly definitionDict: {[key in keyof T]: ISiDataType}, ) { super(); } typeSpecificIsValueValid(value: SiDictValue): boolean { return this.keysOfT.every((key) => ( value[key] !== undefined )); } typeSpecificValueToString(value: SiDictValue): 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 { const dictValue: SiPartialDictValue = {}; 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; } typeSpecificUpdateData(data: ISiStorageData, newValue: SiDictValue): 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)[]; } }