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

Benoit Marchant marchant at mac.com
Thu Mar 23 05:48:01 UTC 2017


+💯

> On Mar 20, 2017, at 11:15 PM, /#!/JoePea <joe at trusktr.io> wrote:
> 
> 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,
>   ["​bar​"] => ​OtherObject​,
> }
> ```
> 
> 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)
> m.add('​bar​', ​OtherObject​)
> ​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 example:
> 
> ```js
> let m = new ReversedWeakMap
> 
> function main() {
>   m.set('foo', {})
>   console.log(m.get('foo')) // {}
> }()
> 
> main()
> 
> // GC would have to be guaranteed to have happened at this point.
> 
> console.log(m.get('foo')) // undefined
> 
> ```
> 
> 
> /#!/JoePea
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170322/885bca1a/attachment.html>


More information about the es-discuss mailing list