Thoughts on WeakMaps

Allen Wirfs-Brock allen at wirfs-brock.com
Tue Jun 7 09:53:53 PDT 2011


On Jun 7, 2011, at 9:02 AM, Brendan Eich wrote:

> On Jun 7, 2011, at 7:41 AM, David Bruant wrote:
> 
>> Le 06/06/2011 17:31, David Bruant a écrit :
>>> myWeakMap.set(key, value) doesn't return anything. It could return the previous value for the key (if such a thing exists). Is it intentional that the set function doesn't return anything?
>> Anyone has thoughts on this point?
> 
> I've used that "return the old value" pattern with success before. Mark may have a reason for not using it here, though.

The "return the old value" pattern is no doubt more efficient in situations where you need to use the old value after replacing it.  I don't know how common that really is.  If we wanted to avoid an extra hash lookkup for read-modify-write sequences we might provide a method whose semantics were:
    Map.prototype.update = function(key,mutator) {
         //the follow get and set calls may be internally optimized to perform only a single hash lookup
         let old = this.get(key);
         let new = mutator(old);
         this.set(key,new);
         return new;
    }

Of course, it's questionable whether by the time you create and pass the mutator you have actually saved the cost of the extra lookup.  Also, the implementation would probably have to fall back to doing a second lookup if the mutator did anything that changed the internal structure of the map.

Allen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110607/7a735468/attachment.html>


More information about the es-discuss mailing list