Proposal: Add Map.prototype.putIfAbsent

Andrea Giammarchi andrea.giammarchi at gmail.com
Thu Oct 11 19:30:53 UTC 2018


I think it boils down to the fact `.put(value)` is a well known method
outside the JS world that returns the value.

I honestly would **love** to have `.put` in Map, Set, and Weak friends, so
that the whole thing would be:

```js
const value = map.has(key) ? map.get(key) : map.put(key, createValue());

// with the more than common safe shortcut as
const value = map.get(key) || map.put(key, createValue());
```

If you understand that `put` by default returns the value you are putting,
`putIfAbsent` makes perfect sense as a method that `put` the value only if
absent but like `put` would return either the present one, or the one
stored 'cause absent.




On Thu, Oct 11, 2018 at 6:19 PM Jack Lu <jacklu at jacklu.me> wrote:

> Don't you think the name `putIfAbsent` is somewhat misleading? In the
> sense that the purpose of this function is to get the value, with a side
> effect of setting a default value when it's
> absent._______________________________________________
> 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/20181011/54980064/attachment.html>


More information about the es-discuss mailing list