function createWeakCache() {
const cache = new Map();
const registry = new FinalizationRegistry((key) => cache.delete(key));
return {
set(key, value) {
cache.set(key, new WeakRef(value));
registry.register(value, key);
},
get(key) {
return cache.get(key)?.deref() ?? null;
},
has(key) {
return this.get(key) !== null;
},
};
}
// Usage
const imgCache = createWeakCache();
const img = new Image();
img.src = '/hero.jpg';
imgCache.set('hero', img);
console.log(imgCache.get('hero')); // Image element (while alive)
Create a free account and build your private vault. Share publicly whenever you want.