SPB Git forge

spb/cancerindex

Public
37commits 1branches 0releases
2.9 MBsize
maindefault branch
10 days agolast push
TypeScript 97.2% SQL 1.5% CSS 0.6% JavaScript 0.5%
814 B · 31 lines typescript
Raw Blame History
1/** Minimal in-process TTL cache (single node, no eviction pressure expected). */2export class TtlCache<V> {3  private store = new Map<string, { value: V; expires: number }>();4  constructor(private readonly ttlMs: number) {}56  get(key: string): V | undefined {7    const hit = this.store.get(key);8    if (!hit) return undefined;9    if (hit.expires < Date.now()) {10      this.store.delete(key);11      return undefined;12    }13    return hit.value;14  }1516  set(key: string, value: V): V {17    this.store.set(key, { value, expires: Date.now() + this.ttlMs });18    return value;19  }2021  async getOrLoad(key: string, load: () => Promise<V>): Promise<V> {22    const hit = this.get(key);23    if (hit !== undefined) return hit;24    return this.set(key, await load());25  }2627  clear(): void {28    this.store.clear();29  }30}31