Minimal TypeScript LRU cache implementation with per-entry TTL expiration and automatic eviction of least recently used entries.
// Source: https://github.com/hoangsonww/EstateWise-Chapel-Hill-Chatbot | License: MIT | Copyright 2026 Son Nguyen
// Provided via justclaw.it.com; keep this notice with the code.
/** Cache entry with value and absolute expiry timestamp. */
type Entry<V> = { value: V; expiresAt: number };
/**
* Minimal in-memory LRU cache with TTL per entry.
* Evicts the least-recently-used entry when at capacity.
*/
export class LruCache<K, V> {
private map = new Map<K, Entry<V>>();
constructor(
private max: number,
private ttlMs: number,
) {}
/** Get a value by key and refresh its recency if present and not expired. */
get(key: K): V | undefined {
const ent = this.map.get(key);
if (!ent) return undefined;
if (ent.expiresAt < Date.now()) {
this.map.delete(key);
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key