mergeWith method

Map<K, V> mergeWith(
  1. Map<K, V> other,
  2. V mergeFunction(
    1. V,
    2. V
    )
)

Merges this map with another map using a merge function for conflicts.

Example:

{'a': 1, 'b': 2}.mergeWith({'b': 3, 'c': 4}, (a, b) => a + b);
// {'a': 1, 'b': 5, 'c': 4}

Implementation

Map<K, V> mergeWith(Map<K, V> other, V Function(V, V) mergeFunction) {
  final result = <K, V>{...this};
  other.forEach((key, value) {
    result[key] = result.containsKey(key)
        ? mergeFunction(result[key] as V, value)
        : value;
  });
  return result;
}