Something went wrong. Try again.
message board on atproto atchan.net
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849interface Entry<V> { value: V expires: number}
export class TtlStore<K, V extends NonNullable<unknown> | null> { readonly #entries = new Map<K, Entry<V>>() readonly #ttl: number readonly #miss_ttl: number readonly #max: number
constructor(ttl: number, max: number, miss_ttl: number = ttl) { this.#ttl = ttl this.#miss_ttl = miss_ttl this.#max = max }
get(key: K): V | undefined { const entry = this.#entries.get(key) if (!entry) return undefined if (Date.now() > entry.expires) { this.#entries.delete(key) return undefined } return entry.value }
set(key: K, value: V): void { const ttl = value === null ? this.#miss_ttl : this.#ttl
this.#entries.delete(key) this.#entries.set(key, { value, expires: Date.now() + ttl })
while (this.#entries.size > this.#max) { const oldest = this.#entries.keys().next() if (oldest.done) break this.#entries.delete(oldest.value) } }
del(key: K): void { this.#entries.delete(key) }
clear(): void { this.#entries.clear() }}