1 of 8

Map#updateOrInsert

Bradley Farias - GoDaddy

2 of 8

Map#setIfMissing(key, () => value);

  • Add if a generated value to map if map does not have something at key

~=

if (!map.has(key))� map.set(key, (() => value)());

  • Impact of creating new value is interesting bit
  • May want to update if it isn’t missing?

2 lookups

3 of 8

Other Langs

4 of 8

Map#update(key, old => updated)

~=

old = map.get(key);�updated = (old => updated)(old);�map.set(key, updated);

  • Do we care if it was missing already?
    • Could add 3rd arg as an emplace
    • could throw if missing

2 lookups

5 of 8

Other Langs

6 of 8

Example code with both

if (!map.has(key)) {� map.set(key, defaultValue);�}�map.get(key).doThing();

3 lookups

7 of 8

Map#updateOrInsert(key, old => updated, () => value) => updated | value

  • Combined to single method?
    • When you are inserting missing you often then do an update…
    • When you do an update you don’t want it to be missing…
    • Identity if callback for update handler missing?
    • Error if insert handler missing and missing entry? Error on update if missing entry?
  • Should it be insertOrUpdate? (which is more popular)

8 of 8

Why does this matter?

  • Collection normalization can make the cost of lookup much higher
  • Collection equality hook can also increase lookup costs
  • Convenience while allowing error avoidance
  • We are expanding stdlib