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

T.J. Crowder tj.crowder at farsightsoftware.com
Tue Mar 21 07:34:33 UTC 2017


What are your use cases for it?

Rather than tying it to being a `Map`, I'd prefer to see something like
Java's [`WeakReference`][1]:  You could store the `WeakReference`s in a
`Map` if you wanted strongly-referenced keys with weakly-referenced values.

-- T.J. Crowder

[1]:
http://docs.oracle.com/javase/8/docs/api/java/lang/ref/WeakReference.html

On Tue, Mar 21, 2017 at 6:15 AM, /#!/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/20170321/3edafc21/attachment-0001.html>


More information about the es-discuss mailing list