A different semantics for WeakMap#get default value

Andrea Giammarchi andrea.giammarchi at gmail.com
Mon Jan 16 16:39:08 PST 2012


then the method should be called "*getOrSetIfNotThere(obj, def)*" 'cause
get() would mislead too much

looks to me we are also confusing falsy with undefined ... undefined is
undefined and there's no reason to use a WeakMap to set undefined since I
would expect the WeakMap itself to completely ignore the operation of
"setting" (or relating the keyObject)

Of course if undefined it will always be undefined ... what the second
argument could do instead is to relate *keyObject* with a defined value

var o = wm.get(obj) || def;

is not the same of

var o = wm.get(obj, def);

'cause in first case "*get(obj)*" could be any falsy value while in the
second one *def* will be returned if obj was in the WeakMap and it could be
falsy too but no || operator is used so you are sure that the value of "*o*"
is the one you expected but never undefined ( unless *def* is undefined
itself but then you don't need at all to pass it as second argument )

A "too magic get()" would mean no set is needed anymore so either you call
the method differently, or something is wrong with the logic used with
WeakMaps.

Said that, *has()* could be optimal for all those cases where you want to *
set()* the *keyObject *if not there yet.
This could be optimized in core too as few engines do already for similar
operations and the resulting JS code would be:

if (!wm.has(obj)) {
  wm.set(obj, def);
}
var o = wm.get(obj);

with *has()* the need for second *get()* argument would be kinda pointless
except for all lazy devs out there (ahem ...!)

br

On Mon, Jan 16, 2012 at 11:25 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

> I’m not sure how much this is needed for WeakMaps in particular, but when
> you nest data structures then it’s handy to automatically create an entry
> if it is missing.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120117/f9031e84/attachment.html>


More information about the es-discuss mailing list