Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterable WeakSet in JavaScript
// 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
}
}
}
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
You can’t perform that action at this time.