Created
April 4, 2024 07:25
-
-
Save TheLucifurry/b1256e34b91e3330fa3e50a36a58dbfb to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function saveKeys<P, S>(set: Map<P | S, Set<P | S>>, fromKey: P, toKey: S) { | |
if (set.has(fromKey)) | |
set.get(fromKey)!.add(toKey) | |
else | |
set.set(fromKey, new Set([toKey])) | |
} | |
function deleteKeys<P, S>(set: Map<P | S, Set<P | S>>, fromKey: P, toKey: S) { | |
if (set.has(fromKey)) { | |
const dependantSet = set.get(fromKey)! | |
dependantSet.delete(toKey) | |
if (dependantSet.size === 0) | |
set.delete(fromKey) | |
} | |
} | |
/** | |
* Data structure for managing bidirectional | |
* many-to-many mappings between primary and secondary keys. | |
*/ | |
export class ManyToManyMap<P, S> { | |
private p2s = new Map<P, Set<S>>() | |
private s2p = new Map<S, Set<P>>() | |
add = (primary: P, secondary: S) => { | |
saveKeys(this.p2s, primary, secondary) | |
saveKeys(this.s2p, secondary, primary) | |
} | |
remove = (primary: P, secondary: S) => { | |
deleteKeys(this.p2s, primary, secondary) | |
deleteKeys(this.s2p, secondary, primary) | |
} | |
getSecondaries = (primary: P) => this.p2s.get(primary) | |
getPrimaries = (secondary: S) => this.s2p.get(secondary) | |
hasPrimary = (primary: P) => this.p2s.has(primary) | |
hasSecondary = (secondary: S) => this.s2p.has(secondary) | |
clear = () => { | |
this.p2s.clear() | |
this.s2p.clear() | |
} | |
// TODO: implement iterator methods if you need) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment