diff --git a/src/utilityFunctions.ts b/src/utilityFunctions.ts index 32eb14e09..b0323cbdf 100644 --- a/src/utilityFunctions.ts +++ b/src/utilityFunctions.ts @@ -82,3 +82,69 @@ function createDictionaryWithVector( return returnval; } + +export class TupleMap { + private map: Map> = new Map(); + private value?: V; + + set(keys: K[], value: V): void { + let currentMap: TupleMap = this; + for (const key of keys) { + if (!currentMap.map.has(key)) { + currentMap.map.set(key, new TupleMap()); + } + currentMap = currentMap.map.get(key); + } + currentMap.value = value; + } + + get(keys: K[]): V | undefined { + let currentMap: TupleMap = this; + for (const key of keys) { + currentMap = currentMap.map.get(key) as TupleMap; + if (!currentMap) { + return undefined; + } + } + return currentMap.value; + } + + has(keys: K[]): boolean { + let currentMap: TupleMap = this; + for (const key of keys) { + currentMap = currentMap.map.get(key) as TupleMap; + if (!currentMap) { + return false; + } + } + return currentMap.value !== undefined; + } + + delete(keys: K[]): boolean { + let currentMap: TupleMap = this; + const stack: TupleMap[] = []; + + for (const key of keys) { + if (!currentMap.map.has(key)) { + return false; + } + stack.push(currentMap); + currentMap = currentMap.map.get(key) as TupleMap; + } + + currentMap.value = undefined; + + // Clean up empty nested maps + for (let i = keys.length - 1; i >= 0; i--) { + const parentMap = stack[i]; + const key = keys[i]; + const childMap = parentMap.map.get(key) as TupleMap; + + // Remove map if it has no value and no nested maps + if (!childMap.value && childMap.map.size === 0) { + parentMap.map.delete(key); + } + } + return true; + } +}