Is it possible to implement a two-way weak map in JavaScript? Is it possible to implement a two-way weak map in JavaScript?

Is it possible to make something like a WeakMap that is two way (get a value by its key, or get a key by its value)?

The usage would look like this (in TypeScript syntax to better illustrate):

class TwoWayWeakMap {
  // What goes here?
}

class SomeClass {}

const map = new TwoWayWeakMap<SomeClass, number>()

const o = new SomeClass

map.set(o, 42)

console.log(map.get(o)) // logs "42"
console.log(map.keyFrom(42)) // logs "SomeClass {}" (the `o` object)

At any point later, if o is no longer referenced except inside the TwoWayWeakMap, then the SomeClass object that o was pointing to could be collected.



from Stackoverflow

Comments

Popular posts from this blog

\\u0000 cannot be converted to text error \\u0000 cannot be converted to text error

I am having trouble with this ajax timer it is not doing what I expect and does not execute I am having trouble with this ajax timer it is not doing what I expect and does not execute

How to create @click on select menu in VueJS How to create @click on select menu in VueJS