Function: createLruCache()
API / @xmachines/play-pattern / createLruCache
function createLruCache<V>(maxSize?): KeyValueCache<V>;Defined in: core/src/cache.ts:54
Builds a cache that forgets its least recently used entries.
The algorithm
Two maps, and no list. recent takes every write. When a write takes recent past
maxSize entries, it becomes old and a new recent opens, which drops the previous
old whole. A read of a key of old moves the entry into recent, and THAT is what
makes the eviction an LRU one rather than a FIFO one: an entry that every lookup reads
moves forward, and an entry that nothing reads falls out with the map that holds it.
The cache therefore holds 2 * maxSize + 1 entries at most: old holds maxSize + 1,
and recent holds maxSize. It does no bookkeeping for a read that hits recent.
A stored undefined reads as a miss. Store null for “no value”.
Type Parameters
| Type Parameter |
|---|
V |
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
maxSize | number | 500 | The number of entries that recent holds. It is 1 at the least, and the default is 500. A value that is not a finite number reads as the default, so a cache with no eviction at all cannot happen by accident. |
Returns
A cache. It is not shared: each call builds one.
Example
import { createLruCache } from "@xmachines/core/cache";
const cache = createLruCache<string>(50);cache.set("/profile/:userId", "profile");cache.get("/profile/:userId"); // "profile"