lru-cache-lite-ts
v1.0.0
Published
High-performance, lightweight (<1.5 KB), zero-dependency Least Recently Used (LRU) cache with TTL and hit/miss statistics.
Maintainers
Readme
⚡ lru-cache-lite-ts
Ultra-fast, lightweight (< 1.5 KB), zero-dependency Least Recently Used (LRU) in-memory cache with TTL expiration, eviction hooks, and hit-rate analytics.
💡 Why lru-cache-lite-ts?
Caches in frontend apps, microservices, and serverless functions often only need a clean, bounded key-value store with automatic eviction. Popular alternatives like lru-cache are now heavy (pulling multiple internal polyfills and symbol utilities).
lru-cache-lite-ts provides:
- ⚡ Zero Dependencies & Tiny — Minified to under 1.5 KB using native JavaScript Map iterator ordering.
- ⏳ Per-Item & Global TTL — Set an expiry duration across the cache or per individual key.
- 📊 Real-time Hit/Miss Metrics — Built-in
.stats()to monitor hit rate, misses, and cache efficiency. - 🪝 Eviction Callbacks — Receive notifications via
onEvict(key, value, reason)for resource cleanups. - 🔒 Type-Safe Generics — Full
LruCache<Key, Value>inference. - 📦 Dual ESM & CommonJS — Works in Node.js, Next.js, Vite, Cloudflare Workers, and browsers.
📥 Installation
# npm
npm install lru-cache-lite-ts
# pnpm
pnpm add lru-cache-lite-ts
# yarn
yarn add lru-cache-lite-ts
# bun
bun add lru-cache-lite-ts🚀 Usage & Real-World Examples
1. Basic In-Memory Caching
import { LruCache } from 'lru-cache-lite-ts';
// Limit cache to 3 items:
const userCache = new LruCache<string, { id: string; name: string }>({
max: 3,
});
userCache.set('u1', { id: 'u1', name: 'Alice' });
userCache.set('u2', { id: 'u2', name: 'Bob' });
userCache.set('u3', { id: 'u3', name: 'Charlie' });
// Access 'u1' to make it most recently used:
userCache.get('u1');
// Adding a 4th item evicts 'u2' (the least recently used!):
userCache.set('u4', { id: 'u4', name: 'David' });
console.log(userCache.has('u2')); // false (evicted!)
console.log(userCache.has('u1')); // true (preserved!)2. Time-To-Live (TTL) Auto-Expiration
import { LruCache } from 'lru-cache-lite-ts';
// Cache responses with default 60-second TTL
const apiCache = new LruCache<string, any>({
max: 500,
ttlMs: 60 * 1000,
});
apiCache.set('endpoint:/api/feed', { articles: ['news1', 'news2'] });
// Or specify custom TTL for an individual sensitive entry (5 seconds):
apiCache.set('session:token_99', { valid: true }, 5000);3. Monitoring Cache Efficiency & Eviction Hooks
import { LruCache } from 'lru-cache-lite-ts';
const cache = new LruCache<string, string>({
max: 100,
onEvict: (key, val, reason) => {
console.log(`Evicted key "${key}" due to ${reason}`);
},
});
cache.set('file1', 'cached_data');
cache.get('file1'); // Hit
cache.get('file2'); // Miss
console.log(cache.stats());
// {
// hits: 1,
// misses: 1,
// hitRate: 0.5,
// size: 1,
// max: 100
// }📖 API Reference
new LruCache<K, V>(options) / createLruCache<K, V>(options)
Options (LruCacheOptions<K, V>):
| Property | Type | Default | Description |
|---|---|---|---|
| max | number | Required | Maximum number of keys retained before eviction |
| ttlMs | number | undefined | Default expiration lifetime in milliseconds |
| onEvict | (key, value, reason) => void | undefined | Callback when key is purged ('capacity' or 'ttl') |
Methods:
| Method | Returns | Description |
|---|---|---|
| .get(key) | V \| undefined | Retrieves value and marks key as most recently used |
| .set(key, value, ttlMs?) | this | Inserts or updates key. Evicts LRU key if at capacity |
| .peek(key) | V \| undefined | Reads value without refreshing its recency rank |
| .has(key) | boolean | Checks existence and expiration without updating recency |
| .delete(key) | boolean | Deletes specific key |
| .clear() | void | Clears all entries and resets metrics |
| .stats() | object | Returns hits, misses, hitRate, and current size |
💖 Support the Project
If lru-cache-lite-ts speeds up your applications, please consider supporting ongoing development:
👉 Sponsor @Piratha97 on GitHub Sponsors
📄 License
MIT © 2026 Pirapaakaran Pirathapan
