tc39 / proposal-collection-methods

https://tc39.github.io/proposal-collection-methods/
Other
172 stars 8 forks source link

Map.prototype.getWithDefault #39

Closed halfzebra closed 4 years ago

halfzebra commented 4 years ago

Hello friends, thanks for maintaining this proposal! 🙌

I've been wondering whether there is any interest in Map.prototype.getWithDefault method which would allow retrieving values by a key, while supplementing a default value to be returned in case of the element's absence.

const colors = new Map([
  ['roof', 'green'],
  ['wall', 'yellow'],
])

const entry = cache.getWithDefault('door', 'red') // returns 'red'

This would enable developers to write less checks and resolve map reads in one expression.

What do you think?

peteboere commented 4 years ago

I think this is already well covered by the new nullish operator

cache.get('door')` ?? 'red'
halfzebra commented 4 years ago

Thanks for pointing this out! 👍

Good point, I think it makes sense to close this then.

hax commented 4 years ago

No. They have subtle semantic difference.

The semantic of cache.get('door') ?? 'red' means cache.get('door') === null || cache.get('door') === undefined ? cache.get('door') : 'red'

The semantic of cache.getWithDefault('door', 'red') should be cache.has('door') ? cache.get('door') : 'red'

In fact, we don't need Map.prototype.getWithDefault, we could just upgrade Map.prototype.get to accept the optional second argument.

See similar discussion at https://github.com/tc39/proposal-upsert/issues/20 .

halfzebra commented 4 years ago

Good point, there is indeed a difference in semantics. 👍

I would like to see something like that being implemented/ This proposal is inspired by this style of unwrapping the value, which might be not present Maybe.withDefault.

Upsert looks good to me, although it might be solving a slightly different challenge.

Do you think it's worth reopening this issue?

hax commented 4 years ago

Do you think it's worth reopening this issue?

I think getWithDefault is out of the scope of this proposal and should be discussed (as an alternative solution) in upsert proposal.

halfzebra commented 4 years ago

Thanks for the suggestion, I will open an issue there.