import { Variable, type MustacheValue } from "./Variable" import { hasDuplicates } from "./helperFunctions" /** * A generic class to create a view (the context for a Mustache.render() call). This class's _collection property holds all the names in any subsequently created variable registry via the allKeys getter. * @todo Prevent duplicates */ export class VariableView { private static _collection:VariableView[] = []; static get all(): Record { return Object.fromEntries( VariableView._collection.flatMap(view => Object.entries(view)) ); }; static get allNames(){ return VariableView._collection.map(variable=>Object.keys(variable)).flat(); }; [key: string]: MustacheValue; // [key:string] gives permission for arbitrary string keys constructor(...variableValuePairs:Variable[]){ variableValuePairs.forEach(pair=>{ this[pair.key] = pair.value; if (VariableView.allNames.includes(pair.key)){ console.warn(`Master variable list already contains the variable ${pair.key} being added by ${this.constructor.name}.`); console.trace(); } }); VariableView._collection.push(this); if (hasDuplicates(variableValuePairs.map(pair=>pair.key))){ console.warn(`Duplicated values in ${this.constructor.name}. (And yes, I should and will add where those occur.)`) }; }; add(...variableValuePair:Variable[]){ variableValuePair.forEach(pair=>{ // It would be a good idea to include a check for duplicate keys this[pair.key] = pair.value }) }; replace(variableKey:string,value:string|Function){ this[variableKey] = value; }; };