demo · v143
Counter & group-by patterns
Three patterns that get one line shorter and one bug-class smaller with Map.prototype.getOrInsert. Word counter, group-by-key, and dedup counter. Each shows the old "has + get + set" dance vs the new getOrInsertComputed call.
Pick a pattern
before — manual
after — getOrInsertComputed
Input
Output
Snippet
// v143
function countWords(text) {
const m = new Map();
for (const w of text.split(/\s+/)) {
m.set(w, (m.getOrInsert(w, 0)) + 1);
}
return m;
}
// Or, with the Computed variant for expensive defaults:
function groupBy(items, keyFn) {
const m = new Map();
for (const it of items) {
m.getOrInsertComputed(keyFn(it), () => []).push(it);
}
return m;
}