Use cases for WeakMap

David Bruant david.bruant at labri.fr
Sat May 14 15:49:21 PDT 2011


Le 15/05/2011 00:37, Oliver Hunt a écrit :
> It's not that they're impossible, it's that they all reduce to a strong map with automatic deletion, rather than "WeakMap".
>
> Take any form of weak cache, say for example you want to cache the object representation that's the result of an XHR (or some such)
>
> eg.  you want to do
>
> function getObject(url) {
>     var result = myCache.get(url);
>     if (result)
>        return result;
>     result = Object.freeze(JSON.parse(loadURLWithSynchXHR(url).responseText));
>     myCache.set(url, result);
>     return result;
> }
>
> Except you this doesn't work, because the map needs to have an object key, so the string is not allowed, we have to do new String(url) or some such as the key, so for a use case like this we need a map from string primitive to String object, so making the map a strong map.
Since your getObject function has a string as unique argument, there is
no other choice than doing a strong map. Strings are primitive values.
They are copied, not passed by reference like objects. If you want to
index things on primitive values, you'll have to delete them yourself
(with a timer maybe?).

David


More information about the es-discuss mailing list