Default value argument for Map/WeakMap.prototype.get()

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Nov 28 11:27:31 PST 2012


it was there and it has been removed ... curious to see if it will be back.

Said that, same way you do

obj.prop = obj.prop || def;

you can do

obj.set(prop, obj.get(prop) || {});

I know it's not the equivalent since you might want to be able to set null,
false, "", NaN, etc etc ... but it's easy to add utilities to current logic
while it might be ambiguous to change defaultValue behavior later on.

As example, I might want to consider an inherited property as valid value
while what you are suggesting, in a more generic approach, is not
considering inheritance because the property is not "own"

br






On Wed, Nov 28, 2012 at 11:07 AM, Jason Orendorff <jason.orendorff at gmail.com
> wrote:

> I propose adding an optional second argument to the .get() method on Map
> and WeakMap.
>
>     Map.prototype.get(key[, defaultValue])
>
> The default value would be returned only when the given key is not in the
> map. That is, in the last step of the spec for these two methods, instead
> of "Return undefined", it would say "Return defaultValue".
>
> Python and Ruby have this. (In Ruby it's called "fetch".) It's handy in
> cases like:
>
>     var counts = new Map;
>     for (let word of words)
>         counts.set(word, counts.get(word, 0) + 1);
>
> -j
>
>
> _______________________________________________
> 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/20121128/950839a5/attachment-0001.html>


More information about the es-discuss mailing list