Memoization with WeakMap support for object keys, LRU eviction, and TTL
npm install @philiprehberger/memo-mapMemoization with WeakMap support for object keys, LRU eviction, and TTL.
npm install @philiprehberger/memo-map
import { memoize } from '@philiprehberger/memo-map';
// Basic memoization
const expensive = memoize((n: number) => {
console.log('computing...');
return n * n;
});
expensive(5); // computing... => 25
expensive(5); // => 25 (cached)
// With LRU eviction and TTL
const cached = memoize(fetchUser, {
maxSize: 100,
ttl: 60_000, // 1 minute
});
// Object args use WeakMap automatically
const getSize = memoize((obj: object) => Object.keys(obj).length);
// Custom key function
const byId = memoize(
(user: { id: number; name: string }) => user.name.toUpperCase(),
{ key: (user) => user.id },
);
memoize<T>(fn, options?)Wraps fn with memoization. Returns the memoized function with additional properties.
Options:
| Option | Type | Description |
|---|---|---|
maxSize | number | Maximum cache entries (LRU eviction) |
ttl | number | Time-to-live in milliseconds |
key | (...args) => unknown | Custom cache key function |
Returned function extras:
.cache — The underlying Map instance.clear() — Clear all cached entriesKey resolution (default):
WeakMapJSON.stringify(args)npm install
npm run build
npm test
If you find this project useful: