Files
bworld/server/game/lru.ts
T

56 lines
1.3 KiB
TypeScript

// a Map that forgets the least recently used entries past max_size
export class LruMap<K, V> {
#map = new Map<K, V>();
#newest: K | undefined;
readonly max_size: number;
// called with what's forgotten for being the least recently used
#on_evict?: (key: K, value: V) => void;
constructor(max_size: number, on_evict?: (key: K, value: V) => void) {
this.max_size = max_size;
this.#on_evict = on_evict;
}
get(key: K): V | undefined {
const value = this.#map.get(key);
// already the most recent, the same key over and over is common
if (key === this.#newest) return value;
if (value !== undefined) {
this.#newest = key;
// maps keep insertion order, so re-inserting moves it to the back
this.#map.delete(key);
this.#map.set(key, value);
}
return value;
}
set(key: K, value: V) {
this.#newest = key;
this.#map.delete(key);
this.#map.set(key, value);
if (this.#map.size > this.max_size) {
const [oldest, value] = this.#map.entries().next().value!;
this.#map.delete(oldest);
this.#on_evict?.(oldest, value);
}
}
// without counting as a use
has(key: K) {
return this.#map.has(key);
}
// get without counting as a use
peek(key: K): V | undefined {
return this.#map.get(key);
}
delete(key: K) {
this.#map.delete(key);
}
get size() {
return this.#map.size;
}
}