Thoughts on WeakMaps

Allen Wirfs-Brock allen at wirfs-brock.com
Tue Jun 7 08:29:41 PDT 2011


On Jun 7, 2011, at 8:02 AM, Mark S. Miller wrote:

> On Tue, Jun 7, 2011 at 7:41 AM, David Bruant <david.bruant at labri.fr> 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 prefer the present behavior because
> 
> 1) I'll be proposing that WeakMaps have "has" and "delete" methods so they better match the Map proposal and what Mozilla has already implemented. Given this, the four methods seem even more field-like. Setters don't return anything. [[Put]] doesn't return anything. And "foo.bar = baz" returns baz, not the previous value of foo.bar.

but weakmap set can't be used in a LHS context, so it won't ever look like a "field" access
> 
> 2) The current API makes it easier to reason about when you're using read-rights vs write-rights. A bound set method (weakMap.set.bind(weakMap)) can be handed out to give rights to store into a given weak map without giving out rights to retrieve from it. And vice versa for a bound get method. 

    function (k,v) {weakMap.set(k,v)}
isn't much longer for creating such a function to hand out.  ((k,v)->void weakMap.set(k,v)) is actually shorter

> 
> 3) If we do this for "set", we'll be tempted to do it for "delete". Let's keep things simple

In such situations, I would prefer that set return the map.  Then set can be "cascaded":

   getMyMap().set(key1,value1).set(key2,value2).set(key3,value3);

or if you prefer vertical:

   getMyMap()
       .set(key1,value1)
       .set(key2,value2)
       .set(key3,value3);

Of course, if we do this we should apply the same pattern to all similar methods we are adding...

Allen

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


More information about the es-discuss mailing list