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

Andrea Giammarchi andrea.giammarchi at gmail.com
Wed Nov 28 12:11:10 PST 2012


thing is ... it's not really that trivial.

What if you decide to define a property/value as undefined ?

In this case the equivalent is, AFAICT

function d(map, key, defaultValue) {
  return map.has(key) ? map.get(key) : defaultValue;
}

so that

counts.set(word, d(counts, word, 0) + 1);

the fact is that map.set({}, undefined) is allowed/valid so it's easy to go
down to ambiguity

var m = new Map;
m.set(m, undefined);
m.has(m); // true


br





On Wed, Nov 28, 2012 at 11:52 AM, Domenic Denicola <
domenic at domenicdenicola.com> wrote:

>  Using https://github.com/substack/defined you can do
>
> var d = require("defined");
> var x = d(m.get("key"), defaultValue);
>
> Not sure if this is an argument for adding default value because this
> module is so ridiculous ... or against it since it’s so trivial to get the
> functionality yourself.
>
>  *From:* Andrea Giammarchi
> *Sent:* November 28, 2012 14:27
> *To:* Jason Orendorff
> *CC:* es-discuss
> *Subject:* Re: Default value argument for Map/WeakMap.prototype.get()
>
> 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/1f41aa4d/attachment.html>


More information about the es-discuss mailing list