upsert method
void
upsert(
- K key,
- V insert(),
- V update(
- V existing
If key absent: thiskey = insert(); else thiskey = update(thiskey).
Audited: 2026-06-12 11:26 EDT
Implementation
void upsert(K key, V Function() insert, V Function(V existing) update) {
// Branch on presence, not on the looked-up value: a key can be present with
// a null value, and treating that as "absent" would wrongly call insert().
if (!containsKey(key)) {
this[key] = insert();
} else {
// The `is V` test both narrows the nullable lookup to non-null and skips
// the rare case where the stored value is null (V itself nullable), so
// update only ever receives a genuine existing V.
final v = this[key];
if (v is V) this[key] = update(v);
}
}