merge<K, V> static method

  1. @useResult
Map<K, V> merge<K, V>(
  1. Map<K, V> a,
  2. Map<K, V> b, {
  3. required V resolve(
    1. K key,
    2. V a,
    3. V b
    ),
})

Merges a and b, using resolve to resolve conflicting entries.

See putAll for merging maps in-place.

final foo = {'a': 1, 'b': 2};
final bar = {'a': 1, 'b': 3};

final merged = Maps.merge(foo, bar, resolve: (k, v1, v2) => min(v1, v2));

print(merged); // {'a': 1, 'b': 2}

Implementation

@useResult static Map<K, V> merge<K, V>(Map<K, V> a, Map<K, V> b, {required V Function(K key, V a, V b) resolve}) {
  final result = Map.of(a);
  for (final MapEntry(:key, :value) in b.entries) {
    final existing = a[key];
    result[key] = existing == null ? value : resolve(key, existing, value);
  }

  return result;
}