platform-common-utilities/packages/merge_map/lib/belatuk_merge_map.dart

37 lines
1.1 KiB
Dart
Raw Normal View History

2021-09-11 14:09:54 +00:00
/// Exposes the [mergeMap] function, which... merges Maps.
library angel3_merge_map;
dynamic _copyValues<K, V>(
2021-09-12 00:03:13 +00:00
Map<K, V> from, Map<K, V?> to, bool recursive, bool acceptNull) {
2021-09-11 14:09:54 +00:00
for (var key in from.keys) {
if (from[key] is Map<K, V> && recursive) {
2021-09-12 00:03:13 +00:00
if (to[key] is! Map<K, V>) {
2021-09-11 14:09:54 +00:00
to[key] = <K, V>{} as V;
}
2021-09-12 00:03:13 +00:00
_copyValues(from[key] as Map, to[key] as Map, recursive, acceptNull);
2021-09-11 14:09:54 +00:00
} else {
2021-09-12 00:03:13 +00:00
if (from[key] != null || acceptNull) {
to[key] = from[key];
}
2021-09-11 14:09:54 +00:00
}
}
}
/// Merges the values of the given maps together.
///
/// `recursive` is set to `true` by default. If set to `true`,
/// then nested maps will also be merged. Otherwise, nested maps
/// will overwrite others.
///
/// `acceptNull` is set to `false` by default. If set to `false`,
/// then if the value on a map is `null`, it will be ignored, and
/// that `null` will not be copied.
Map<K, V> mergeMap<K, V>(Iterable<Map<K, V>> maps,
{bool recursive = true, bool acceptNull = false}) {
var result = <K, V>{};
2021-09-12 00:03:13 +00:00
for (var map in maps) {
2021-09-11 14:09:54 +00:00
_copyValues(map, result, recursive, acceptNull);
2021-09-12 00:03:13 +00:00
}
2021-09-11 14:09:54 +00:00
return result;
}