Skip to content

Commit

Permalink
add tuple map class
Browse files Browse the repository at this point in the history
  • Loading branch information
bmschmidt committed Sep 9, 2024
1 parent 3f1e0d5 commit 290e0fe
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions src/utilityFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,69 @@ function createDictionaryWithVector(

return returnval;
}

export class TupleMap<K = Object, V = Object> {
private map: Map<K, TupleMap<K, V>> = new Map();
private value?: V;

set(keys: K[], value: V): void {
let currentMap: TupleMap<K, V> = this;
for (const key of keys) {
if (!currentMap.map.has(key)) {
currentMap.map.set(key, new TupleMap<K, V>());
}
currentMap = currentMap.map.get(key);
}
currentMap.value = value;
}

get(keys: K[]): V | undefined {
let currentMap: TupleMap<K, V> = this;
for (const key of keys) {
currentMap = currentMap.map.get(key) as TupleMap<K, V>;
if (!currentMap) {
return undefined;
}
}
return currentMap.value;
}

has(keys: K[]): boolean {
let currentMap: TupleMap<K, V> = this;
for (const key of keys) {
currentMap = currentMap.map.get(key) as TupleMap<K, V>;
if (!currentMap) {
return false;
}
}
return currentMap.value !== undefined;
}

delete(keys: K[]): boolean {
let currentMap: TupleMap<K, V> = this;
const stack: TupleMap<K, V>[] = [];

for (const key of keys) {
if (!currentMap.map.has(key)) {
return false;
}
stack.push(currentMap);
currentMap = currentMap.map.get(key) as TupleMap<K, V>;
}

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<K, V>;

// Remove map if it has no value and no nested maps
if (!childMap.value && childMap.map.size === 0) {
parentMap.map.delete(key);
}
}
return true;
}
}

0 comments on commit 290e0fe

Please sign in to comment.