Skip to main content

Import

What it does

CacheManager provides a generic in-memory cache with time-to-live (TTL) expiration, LRU eviction when maxSize is reached, optional localStorage persistence, and built-in hit/miss statistics. Use it to cache expensive computations, API responses, or any data that benefits from short-lived memoization.

Constructor

CacheManagerConfig

Factory

Convenience function that returns a new CacheManager instance.

Methods

get<T>(key)

Returns the cached value or undefined if the key is missing or expired.

set<T>(key, value, options?)

Stores a value. An optional per-entry ttl overrides defaultTTL.

getOrCompute<T>(key, fn, options?)

Returns the cached value if present; otherwise calls fn, caches the result, and returns it. Useful for stale-while-revalidate patterns.

delete(key)

Removes a single entry. Returns true if the key was found.

has(key)

Returns true if the key exists and has not expired.

clear()

Removes all entries from the cache.

size()

Returns the current number of cached entries.

keys()

Returns an array of all active (non-expired) cache keys.

stats()

Returns cache performance statistics.

Examples

Basic TTL cache

Compute-on-miss pattern

Monitoring cache performance

When maxSize is reached, the least-recently-used entry is evicted to make room for new ones. This ensures the cache stays within its configured bounds.
Use getOrCompute instead of manual get / set sequences to avoid cache stampedes — concurrent callers for the same key will reuse the same computation.
enableLocalStorage serializes values with JSON.stringify. Non-serializable values (functions, circular references) will fail silently or lose fidelity.