3 ms·
> Upsert (https://github.com/tc39/proposal-upsert https://github.com/tc39/proposal-upsert): [Weak]Map.prototype.getOrInsert(), [Weak]Map.prototype.getOrInsertCo
by jdthedisciple 5mo ago
> Upsert (https://github.com/tc39/proposal-upsert https://github.com/tc39/proposal-upsert): [Weak]Map.prototype.getOrInsert(), [Weak]Map.prototype.getOrInsertComputed()
Their usage of upsert appears different than I was used to:
Me: Upsert = Update or Insert
Them: Upsert = Get or Insert
- bakkoting 5mo agoThe proposal used to do more thing and we didn't change the URL after we ultimately arrived at this set of APIs.
- OptionOfT 5mo agoReminds me of the weird C++ map operator[] behavior. If you use that operator and the value doesn't exist, it'll default create one and return a reference to that. And as I'm writing this I realize why... references cannot be `null`.
- rtpg 5mo agowhat is the value of an "update or insert" call on `Map`? is that not just set? `getOrInsert` here seems to be the Python "set_default" method on dicts, which is very useful at avoiding tedium in some basic data munging
- AdieuToLogic 5mo ago> what is the value of an "update or insert" call on `Map`? It gives a caller the option of alternate logic based on the existence, or lack thereof, of a value. > is that not just set? No. The semantics of a "set" operation would overwrite an existing entry (if one exists).
- Klaster_1 5mo agoI do this all the time, getOrInsert would come really handy: you need something from a Map-backed storage, but the value may be unset, so you first check if it's undefined, set the default value, and then use that. Example: update(store, (draft) => { if (!draft.alertConfigurations.has(req.params.clusterId)) draft.alertConfigurations.set(req.params.clusterId, new Map()); const clusterAlerts = draft.alertConfigurations.get(req.params.clusterId); req.body.forEach((alert) => clusterAlerts.set(alert.id, { ...alert, predefined: false })); });
- AdieuToLogic 5mo ago> Their usage of upsert appears different than I was used to: > Them: Upsert = Get or Insert I agree that their choice of labeling the proposal as "upsert" is less than ideal. However, this functionality is reminiscent of a very useful Perl capability known as autovivification[0] as described in the motivation section: A common problem when using a Map or WeakMap is how to handle doing an update when you're not sure if the key already exists in the map. 0 - https://en.wikipedia.org/wiki/Autovivification https://en.wikipedia.org/wiki/Autovivification