Skip to content

Instantly share code, notes, and snippets.

@seanlinsley
Last active May 25, 2025 08:12
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
}
}
}
@cubuspl42
Copy link

While I agree that it might be possible to implement a working weak set using the technique you suggest, this implementation has issues. It's a (quasi-) bag, not a set. There's no attempt to ensure that a single element is added to the set only once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment