Skip to content

Instantly share code, notes, and snippets.

@phillmac
Forked from seanlinsley/iterable_weak_set.js
Last active June 24, 2020 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillmac/797ed6c50acfeb30672241c18ac68e07 to your computer and use it in GitHub Desktop.
Save phillmac/797ed6c50acfeb30672241c18ac68e07 to your computer and use it in GitHub Desktop.
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