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.
NOTE! The second argument to map.set(k, v)
must be allowed to be anything, not just objects. v
can be a number
, for example.