mergeMaps<K, V> function

Map<K, V> mergeMaps<K, V>(
  1. Map<K, V> map1,
  2. Map<K, V> map2,
  3. {V value(
    1. V,
    2. V
    )?}
)

Returns a new map with all key/value pairs in both map1 and map2.

If there are keys that occur in both maps, the value function is used to select the value that goes into the resulting map based on the two original values. If value is omitted, the value from map2 is used.

Implementation

Map<K, V> mergeMaps<K, V>(Map<K, V> map1, Map<K, V> map2,
    {V Function(V, V)? value}) {
  var result = Map<K, V>.of(map1);
  if (value == null) return result..addAll(map2);

  map2.forEach((key, mapValue) {
    result[key] =
        result.containsKey(key) ? value(result[key] as V, mapValue) : mapValue;
  });
  return result;
}