Hacker News new | ask | show | jobs
by rtpg 30 days ago
what 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

2 comments

I 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 }));
    });
> 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).