merge method

Map<K, V> merge(
  1. Map<K, V>? others, {
  2. K convertKeys(
    1. K key
    )?,
  3. V convertValues(
    1. V value
    )?,
})

Merges elements of others into Map.

You can use convertKeys to convert keys when merging others.

You can use convertValues to convert values when merging others.

Mapothersの要素をマージします。

othersをマージする際のキーをconvertKeysで変換できます。

othersをマージする際の値をconvertValuesで変換できます。

final map = {"a": 1, "b": 2, "c": 3};
final others = {"d": 4, "e": 5};
final merged = map.merge(others, convertKeys: (key) => "merged_$key", convertValues: (value) => value * 2); // {"a": 1, "b": 2, "c": 3, "merged_d": 8, "merged_e": 10}

Implementation

Map<K, V> merge(
  Map<K, V>? others, {
  K Function(K key)? convertKeys,
  V Function(V value)? convertValues,
}) {
  others ??= const {};
  final res = <K, V>{};
  for (final tmp in entries) {
    res[tmp.key] = tmp.value;
  }
  for (final tmp in others.entries) {
    final key = convertKeys?.call(tmp.key) ?? tmp.key;
    final value = convertValues?.call(tmp.value) ?? tmp.value;
    res[key] = value;
  }
  return res;
}