Created
August 1, 2024 18:29
-
-
Save kitcat-dev/d3ba2f99c2b937d7649cb139f6bff1b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BidirectionalMap<T> { | |
private forwardMap: Map<T, T>; | |
private backwardMap: Map<T, T>; | |
constructor() { | |
this.forwardMap = new Map(); | |
this.backwardMap = new Map(); | |
} | |
set(key: T, value: T): void { | |
const oldValue = this.forwardMap.get(key); | |
if (oldValue) { | |
this.backwardMap.delete(oldValue); | |
} | |
const oldKey = this.backwardMap.get(value); | |
if (oldKey) { | |
this.forwardMap.delete(oldKey); | |
} | |
this.forwardMap.set(key, value); | |
this.backwardMap.set(value, key); | |
} | |
getKey(value: T): T | undefined { | |
return this.backwardMap.get(value); | |
} | |
getValue(key: T): T | undefined { | |
return this.forwardMap.get(key); | |
} | |
hasKey(key: T): boolean { | |
return this.forwardMap.has(key); | |
} | |
hasValue(value: T): boolean { | |
return this.backwardMap.has(value); | |
} | |
deleteKey(key: T): void { | |
if (this.forwardMap.has(key)) { | |
const value = this.forwardMap.get(key); | |
this.forwardMap.delete(key); | |
if (value !== undefined) { | |
this.backwardMap.delete(value); | |
} | |
} | |
} | |
deleteValue(value: T): void { | |
if (this.backwardMap.has(value)) { | |
const key = this.backwardMap.get(value); | |
this.backwardMap.delete(value); | |
if (key !== undefined) { | |
this.forwardMap.delete(key); | |
} | |
} | |
} | |
clear(): void { | |
this.forwardMap.clear(); | |
this.backwardMap.clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment