Skip to content

Instantly share code, notes, and snippets.

@ztrehagem
Created August 30, 2023 04:56
Show Gist options
  • Save ztrehagem/b7e720e7abdbe80194bf7d2bd922673a to your computer and use it in GitHub Desktop.
Save ztrehagem/b7e720e7abdbe80194bf7d2bd922673a to your computer and use it in GitHub Desktop.
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