From dd9bc111f424d476e3bd10b0c47ff4add661ccb8 Mon Sep 17 00:00:00 2001 From: Ben Schmidt Date: Sat, 7 Sep 2024 10:59:09 -0400 Subject: [PATCH] add tuple map class --- src/utilityFunctions.ts | 66 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) 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; + } +}