From 69f6f106563d4b74996aa2d466efe6f7d4730b83 Mon Sep 17 00:00:00 2001 From: Pascal Syma Date: Wed, 11 Dec 2024 15:29:36 +0100 Subject: [PATCH] Add MultiMap util --- utils/multi-map.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 utils/multi-map.ts diff --git a/utils/multi-map.ts b/utils/multi-map.ts new file mode 100644 index 0000000..c356d3c --- /dev/null +++ b/utils/multi-map.ts @@ -0,0 +1,28 @@ +export class MultiMap extends Map { + multiGet(...keys: K): V | undefined { + const firstKey = keys[0]; + const otherKeys = keys.slice(1); + if (!this.has(firstKey)) { + return undefined; + } + + if (otherKeys.length > 0) { + return (this.get(firstKey)! as MultiMap).multiGet(...otherKeys); + } + return this.get(firstKey) as V; + } + + multiSet(value: V, ...keys: K) { + const firstKey = keys[0]; + const otherKeys = keys.slice(1); + + if (otherKeys.length > 0) { + if (!this.has(firstKey)) { + this.set(firstKey, new MultiMap()); + } + (this.get(firstKey) as MultiMap)!.multiSet(value, ...otherKeys); + } else { + this.set(firstKey, value); + } + } +}