Cache
Implements: Store, Serializable
Source: cache.js:53
A tiny in-memory, least-recently-used (LRU) cache.
This class is the showcase's centerpiece: its members exercise nearly every member-level tag the theme renders — parameters, returns, examples, events, deprecation, modifiers, and cross-references.
A
Cacheis not thread-safe across workers. Wrap shared access in a Queue if you need ordered writes.
Eviction follows a strict recency order:
| Operation | Effect on recency |
|---|---|
set(k, v) | marks k most-recently-used |
get(k) | marks k most-recently-used |
has(k) | no change |
Example
Basic usage
const cache = new Cache({ maxSize: 2 });
cache.set('a', 1).set('b', 2);
cache.get('a'); // => 1, and 'a' is now most-recently-used- Since: 1.0.0
- Version: 1.2.0
- Author: The clean-jsdoc-theme team
- See:
- CacheOptions
- createCache for a one-shot factory
Constructor
new Cache([options])
Create a new cache.
Parameters
options(CacheOptions, optional, default: "{}") — Configuration for the cache.options.maxSize(number, optional, default: 100) — Max entries before eviction.options.ttl(number, optional, default: 0) — Per-entry time-to-live in ms.
Instance Methods
set(key, value) -> Cache
Implements: Store#set
Store a value under a key. If the cache is full, the least-recently-used entry is evicted first and a evict event fires.
Parameters
key(string) — The key to store the value under.value(*) — The value to cache.
Returns
Cache— The cache instance, for chaining.
Fires
Cache#event:evict
Example
Calls chain
cache.set('user:1', { name: 'Ada' }).set('user:2', { name: 'Linus' });get(key) -> *
Implements: Store#get
Look up a value by key, marking it as recently used.
Parameters
key(string) — The key to look up.
Returns
*— The cached value, orundefinedif the key is not present.
has(key) -> boolean
Check whether a key is present without affecting its recency.
Parameters
key(string) — The key to test.
Returns
boolean—trueif the key is cached.
remove(key) -> boolean
Remove a single entry.
Since 1.2.0 — prefer
Cache#clearor let entries expire via `ttl`. This method will be removed in 2.0.
Parameters
key(string) — The key to remove.
Returns
boolean—trueif an entry was removed.
clear() -> void
Remove every entry from the cache.
Returns
void
toJSON() -> Object.<string, *>
Implements: Serializable#toJSON
Serialize the cache to a plain object — satisfies Serializable.
Returns
Object.<string, *>— A snapshot of every entry.
Instance Fields
maxSize
The maximum number of entries this cache will hold.
Type
number
ttl
Time-to-live per entry, in milliseconds. 0 means entries never expire.
Type
number
size
The number of entries currently stored.