A WeakRef-based cache that automatically evicts entries when values are garbage collected
npm install weakref-storeimport WeakCache from 'weakref-store';
const cache = new WeakCache({
onEvict(key) {
console.log(`${key} was garbage collected`);
},
});
let value = {data: 'hello'};
cache.set('key', value);
console.log(cache.get('key'));
//=> {data: 'hello'}
console.log(cache.has('key'));
//=> trueType: object
Type: (key) => void
Callback invoked with the key when an entry is evicted by garbage collection.
Returns the value for the key, or undefined if the key does not exist or its value has been garbage collected.
Set a key-value pair. The value must be a non-null object or a function. Throws TypeError for primitives or null, leaving an existing entry for that key unchanged.
Returns true if the key exists and the value is still alive.
Removes an entry. Returns true if the entry existed.
The approximate number of entries. May include entries whose values have been collected but not yet finalized.
- WeakRef - MDN WeakRef documentation
- FinalizationRegistry - MDN FinalizationRegistry documentation
MIT