Created
October 3, 2020 08:10
-
-
Save nexpr/6565183775ca7630d8c24a5ade336712 to your computer and use it in GitHub Desktop.
tuple (weakref)
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
| class TupleRegistry { | |
| tuples = [] | |
| constructor() { | |
| this.fregistry = new FinalizationRegistry(() => { | |
| this.tuples = this.tuples.filter(ref => ref.deref()) | |
| }) | |
| } | |
| add(tuple) { | |
| this.fregistry.register(tuple, null) | |
| this.tuples.push(new WeakRef(tuple)) | |
| } | |
| find(values) { | |
| for (const ref of this.tuples) { | |
| const tuple = ref.deref() | |
| if (tuple && tuple.length === values.length && tuple.every((x, i) => values[i] === x)) { | |
| return tuple | |
| } | |
| } | |
| } | |
| } | |
| class Tuple extends Array { | |
| constructor(...a) { | |
| super() | |
| const found = this.constructor.registry.find(a) | |
| if (found) { | |
| return found | |
| } | |
| this.push(...a) | |
| Object.freeze(this) | |
| this.constructor.registry.add(this) | |
| } | |
| static registry = new TupleRegistry() | |
| } | |
| export default Tuple |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment