ttl-cache-lite
v0.1.0
Published
Tiny in-memory cache with TTL expiry and LRU eviction — no dependencies, injectable clock for deterministic tests.
Readme
ttl-cache-lite
Tiny in-memory cache with TTL expiry and LRU eviction. No dependencies, generic <K, V>, and an injectable clock for deterministic tests.
Install
npm install ttl-cache-liteQuick start
import { TtlCache } from 'ttl-cache-lite';
const cache = new TtlCache<string, User>({ maxEntries: 1000, defaultTtlMs: 60_000 });
cache.set(userId, user);
cache.set(sessionId, session, 5 * 60_000); // per-call TTL override
const cached = cache.get(userId); // undefined once expired or evictedWhy TTL and LRU together
A pure TTL cache can still grow unbounded if entries are set faster than they expire; a pure LRU cache can serve stale data indefinitely if it's accessed often enough to stay "hot." Combining both — a hard TTL ceiling on staleness, plus LRU eviction as a size safety valve — covers both failure modes without needing a background sweep timer (expiry is checked lazily on get).
API
new TtlCache<K, V>({ maxEntries?, defaultTtlMs?, now? }).set(key, value, ttlMs?)— per-call TTL overridesdefaultTtlMs; omit both for no expiry.get(key)— returnsundefinedif missing or expired; refreshes LRU recency.has(key)/.delete(key)/.size()/.clear()
License
MIT
