brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Map.getOrInsert() reads a key or stores a default in one call

Javascript
~/tips/tip-js-map-getorinsert-grouping

// Map { "jpg" => ["a.jpg", "c.jpg"], "png" => ["b.png"] }

Group or count items in a Map without the has, set, get dance.

Filling a Map of lists always needs three steps: check if the key exists, set an empty array if not, then get it and push. getOrInsert() does all three.

const byExt = new Map();
for (const file of ["a.jpg", "b.png", "c.jpg"]) {
  const ext = file.split(".").pop();
  byExt.getOrInsert(ext, []).push(file);
}
// Map { "jpg" => ["a.jpg", "c.jpg"], "png" => ["b.png"] }

const cache = new Map();
const user = cache.getOrInsertComputed(id, (key) => loadUserSync(key));

getOrInsert(key, defaultValue) returns the existing value if the key is there. If not, it stores the default and returns that. Since an array is returned by reference, push changes the one in the map.

The second method, getOrInsertComputed(key, callback), only calls the callback when the key is missing. Use it when the default is expensive to make, or when it must be a fresh object each time: with plain getOrInsert the default expression is evaluated on every call, even when it is thrown away. WeakMap has the same two methods.

I would call it brand new: MDN lists Chrome 145, Firefox 144 and Safari 26.2, and Node.js 26 has it too. In older code you will keep seeing map.get(k) ?? map.set(k, []).get(k), which still works fine. For a one-off grouping of an array, Map.groupBy() is shorter; this method shines when you fill a map bit by bit over time.

Further reading: MDN: Map.prototype.getOrInsert(), MDN: Map.prototype.getOrInsertComputed()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link