From 0270dadfd08596c77157ba44db12282e29b66ff7 Mon Sep 17 00:00:00 2001 From: marlonerler Date: Thu, 4 Jul 2024 16:39:52 +0200 Subject: [PATCH] add TwoWayMap --- auxilary.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 auxilary.ts diff --git a/auxilary.ts b/auxilary.ts new file mode 100644 index 0000000..1c556b1 --- /dev/null +++ b/auxilary.ts @@ -0,0 +1,38 @@ +export class TwoWayMap { + private mapAtoB = new Map>(); + private mapBtoA = new Map>(); + + // prepare + private prepareA(a: A) { + if (this.mapAtoB.has(a)) return; + this.mapAtoB.set(a, new Set()); + } + + private prepareB(b: B) { + if (this.mapBtoA.has(b)) return; + this.mapBtoA.set(b, new Set()); + } + + // utility + private getListOnA(a: A) { + return this.mapAtoB.get(a); + } + + private getListOnB(b: B) { + return this.mapBtoA.get(b); + } + + // public + set(a: A, b: B) { + this.prepareA(a); + this.prepareB(b); + + this.getListOnA(a)?.add(b); + this.getListOnB(b)?.add(a); + } + + delete(a: A, b: B) { + this.getListOnA(a)?.delete(b); + this.getListOnB(b)?.delete(a); + } +}