update method
Updates the value for the provided key
.
If the key is present, invokes update with the current value and stores
the new value in the map. However, if ifRemove
is provided, the updated value will
first be tested with it and, if ifRemove
returns true, the value will be
removed from the map, instead of updated.
If the key is not present and ifAbsent
is provided, calls ifAbsent
and adds the key with the returned value to the map.
If the key is not present and ifAbsent
is not provided, return the original map
without modification. Note: If you want ifAbsent
to throw an error, pass it like
this: ifAbsent: () => throw ArgumentError();
.
If you want to get the original value before the update, you can provide the
previousValue
parameter.
Implementation
IMap<K, V> update(
K key,
V Function(V value) update, {
bool Function(K key, V value)? ifRemove,
V Function()? ifAbsent,
Output<V>? previousValue,
}) {
// Contains key.
if (containsKey(key)) {
Map<K, V> map = unlock;
V originalValue = map[key]!;
var updatedValue = update(originalValue);
if (ifRemove != null && ifRemove(key, updatedValue)) {
map.remove(key);
} else {
map[key] = updatedValue;
}
if (previousValue != null) previousValue.save(originalValue);
return IMap._unsafeFromMap(map, config: config);
}
//
// Does not contain key.
else {
if (ifAbsent != null) {
var updatedValue = ifAbsent();
if (previousValue != null) previousValue.save(null);
Map<K, V> map = ListMap.fromEntries(
entries.followedBy([MapEntry(key, updatedValue)]),
sort: config.sort,
);
return IMap._unsafeFromMap(map, config: config);
} else {
if (previousValue != null) previousValue.save(null);
return this;
}
}
}