Loading...
const groups = new Map();
for (const item of items) {
if (!groups.has(item.type)) groups.set(item.type, []);
groups.get(item.type).push(item);
}const groups = new Map();
for (const item of items) {
groups.getOrInsert(item.type, []).push(item);
}getOrInsert() reads or inserts the default in one call, so the key is no longer looked up three times.
map.getOrInsert(key, []).push(item) instead of has(), set() and get().getOrInsertComputed() instead.getOrInsert() overwrite an existing value?No. If the key exists, it returns the stored value and ignores the default.
getOrInsert() and getOrInsertComputed()?getOrInsert() takes a ready default that is created on every call. getOrInsertComputed() takes a callback that runs only when the key is missing.
getOrInsert() too?Yes. WeakMap gets both getOrInsert() and getOrInsertComputed(), with the usual rule that keys must be objects.