add default maps

This commit is contained in:
Matthieu Jolimaitre 2024-12-30 14:59:54 +01:00
parent 69494ebd28
commit e47029c389
2 changed files with 19 additions and 0 deletions

View file

@ -26,3 +26,4 @@ export { Range, range } from "./lib/Range.ts";
export { Event } from "./lib/Event.ts";
export { AsyncPool } from "./lib/AsyncPool.ts";
export { ClassMap } from "./lib/ClassMap.ts";
export { DefaultMap } from "./lib/DefaultMap.ts";

18
src/lib/DefaultMap.ts Normal file
View file

@ -0,0 +1,18 @@
export class DefaultMap<K = string, V = string> {
inner = new Map<K, V>();
constructor(
private def: () => V,
) {}
get(key: K) {
if (!this.inner.has(key)) this.inner.set(key, this.def());
return this.inner.get(key)!;
}
set(key: K, value: V) {
this.inner.set(key, value);
}
[Symbol.iterator] = () => this.inner[Symbol.iterator]();
}