@philiprehberger/memo-map
v0.1.2
Published
Memoization with WeakMap support for object keys, LRU eviction, and TTL
Downloads
28
Readme
@philiprehberger/memo-map
Memoization with WeakMap support for object keys, LRU eviction, and TTL.
Installation
npm install @philiprehberger/memo-mapUsage
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 },
);API
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 underlyingMapinstance.clear()— Clear all cached entries
Key resolution (default):
- Single primitive arg: used directly as key
- Single object arg: stored in a
WeakMap - Multiple args:
JSON.stringify(args)
Development
npm install
npm run build
npm testSupport
If you find this project useful:
