Skip to content

Instantly share code, notes, and snippets.

@seanlinsley
Last active August 2, 2023 03:58
Show Gist options
  • Save seanlinsley/bc10378fd311d75cf6b5e80394be813d to your computer and use it in GitHub Desktop.
Save seanlinsley/bc10378fd311d75cf6b5e80394be813d 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 IterableWeakSet extends Set {
add(el) {
super.add(new WeakRef(el))
}
forEach(fn) {
super.forEach(ref => {
const value = ref.deref()
if (value) fn(value)
})
}
*[Symbol.iterator]() {
for (const ref of super.values()) {
const value = ref.deref()
if (value) yield value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment