// Created on savesnippets.com ยท https://savesnippets.com/BEIDQuXLoyRUTv 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)