Created
August 30, 2023 04:56
-
-
Save ztrehagem/b7e720e7abdbe80194bf7d2bd922673a 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
type Hash = string | number | symbol | object; | |
interface Hashable<K extends Hash> { | |
readonly hash: K; | |
} | |
class FooId implements Hashable<number> { | |
readonly primitive: number; | |
constructor(primitive: number) { | |
this.primitive = primitive; | |
} | |
get hash(): number { | |
return this.primitive; | |
} | |
} | |
class HashedMap<T extends Hashable<K>, V, K extends Hash = T extends Hashable<infer U> ? U : never> { | |
private readonly map: Map<K, V>; | |
constructor(source?: HashedMap<T, V, K>) { | |
this.map = new Map(source?.map); | |
} | |
get({ hash }: T): V | undefined { | |
return this.map.get(hash) | |
} | |
set({ hash }: T, value: V): void { | |
this.map.set(hash, value); | |
} | |
} | |
const map = new HashedMap<FooId, unknown>; | |
map.set(new FooId(1), "one"); | |
const value = map.get(new FooId(1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment