A WeakMap where values (not keys) are weak references?

/#!/JoePea joe at trusktr.io
Tue Mar 21 06:15:29 UTC 2017

Hey all,

I'd like to have something like a WeakMap where the keys can be primitives
and the values are weakly-held Objects, so if there are no more references
to any of the Object values that the entry gets removed from the map.

For example, it might look like this:

  ["foo"] => SomeObject,
"] =>

where if there are no more references to `OtherObject`, then `['bar'] =>
OtherObject` is removed from the map.

Usage would be very similar to WeakMap, like

let m = new ReversedWeakMap

m.add('foo', SomeObject)
​console.log(m.get('bar')) // OtherObject

... time passes, no more references to OtherObject, OtherObject is
collected ...

console.log(m.get('bar'))​ // undefined


I thought of using WeakMap values as keys, and vice versa, but it seems to
be impossible.

I guess maybe it is difficult to add this natively because it would mean
that GC needs to be completely deterministic as far as JS programs go. For

let m = new ReversedWeakMap

function main() {
  m.set('foo', {})
  console.log(m.get('foo')) // {}


// GC would have to be guaranteed to have happened at this point.

console.log(m.get('foo')) // undefined


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170320/003a3a27/attachment.html>

More information about the es-discuss mailing list