import { IFlagCommonField, IFlagSystem, IFlagSystemSave } from './types'; import { FlagCommonField } from './field'; export class FlagSystem implements IFlagSystem { private readonly fieldMap: Map> = new Map(); occupied(field: PropertyKey): boolean { return this.fieldMap.has(field); } insertField(field: PropertyKey, value: T): IFlagCommonField { return this.getOrInsert(field, value); } getField(field: PropertyKey): IFlagCommonField | null { return this.fieldMap.get(field) ?? null; } getOrInsert(field: PropertyKey, defaultValue: T): IFlagCommonField { return this.fieldMap.getOrInsertComputed( field, () => new FlagCommonField(this, field, defaultValue) ); } getOrInsertComputed( field: K, defaultValue: (field: K) => T ): IFlagCommonField { return this.fieldMap.getOrInsertComputed( field, () => new FlagCommonField(this, field, defaultValue(field)) ); } deleteField(field: PropertyKey): void { this.fieldMap.delete(field); } setFieldValue(field: PropertyKey, value: any): void { this.getOrInsert(field, value).set(value); } addFieldValue(field: PropertyKey, value: number): void { this.getOrInsert(field, 0).add(value); } getFieldValue(field: PropertyKey): T | undefined { return this.fieldMap.get(field)?.get(); } getFieldValueDefaults(field: PropertyKey, defaultValue: T): T { return this.getOrInsert(field, defaultValue).get(); } saveState(): IFlagSystemSave { const fields: Map = new Map(); for (const [key, field] of this.fieldMap) { fields.set(key, field.toStructured()); } return { fields }; } loadState(state: IFlagSystemSave): void { this.fieldMap.clear(); for (const [key, data] of state.fields) { const field = new FlagCommonField(this, key, undefined); field.fromStructured(data); this.fieldMap.set(key, field); } } }