Last active
August 2, 2023 03:58
-
-
Save seanlinsley/bc10378fd311d75cf6b5e80394be813d to your computer and use it in GitHub Desktop.
Iterable WeakSet in JavaScript
This file contains hidden or 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 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