Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created October 3, 2020 08:10
Show Gist options
  • Select an option

  • Save nexpr/6565183775ca7630d8c24a5ade336712 to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/6565183775ca7630d8c24a5ade336712 to your computer and use it in GitHub Desktop.
tuple (weakref)
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