-
-
Save phillmac/797ed6c50acfeb30672241c18ac68e07 to your computer and use it in GitHub Desktop.
Iterable WeakSet in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// spec: https://github.com/tc39/proposal-weakrefs | |
// the spec contains an [iterable WeakMap implementation](https://github.com/tc39/proposal-weakrefs#iterable-weakmaps) | |
// NOTE: this WeakSet implementation is incomplete, only does what I needed | |
// In Firefox Nightly, visit about:config and enable javascript.options.experimental.weakrefs | |
class IterableWeakMap extends Map { | |
set(k, v) { | |
super.set(new WeakRef(k), v) | |
} | |
forEach(fn) { | |
super.keys().forEach(ref => { | |
const key = ref.deref() | |
if (key) fn(key) | |
}) | |
} | |
*[Symbol.iterator]() { | |
for (const ref of super.keys()) { | |
const key = ref.deref() | |
if (key) yield key | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
wm = new IterableWeakMap() | |
function showWMKeys() { | |
for (k of wm) { | |
console.dir(k) | |
} | |
} | |
a = {b: 'c'} | |
wm.set(a, true) | |
showWMKeys() | |
typeof a | |
delete a | |
typeof a | |
showWMKeys() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment