Can anybody tell me what does below code does . I am literally lost out the procedure the code does
Map<String, dynamic> deepMerge(Map<String, dynamic> toMerge) {
var source = <String, dynamic>{...this};
for (var key in toMerge.keys) {
if (source.containsKey(key) && source[key] is Map<String, dynamic>) {
if (toMerge[key] is Map<String, dynamic>) {
source[key] = (source[key] as Map<String, dynamic>).deepMerge(toMerge[key]);
}
} else {
source[key] = toMerge[key];
}
}
return source;
}
CodePudding user response:
It recursively traverses a structure of (likely JSON) maps and adds values to it from a parallel structure.
The function is very likely an extension method on Map<String, dynamic>
, so this
refers to such a map, and so does toMerge
.
It starts by creating a copy of this
map, and then goes through all the entries of toMerge
and adds them to the copy as well.
However, if the value of a key in "this" map is itself a map, then it doesn't overwrite that value by the toMerge
value. Instead, if the toMerge
value of the same key is also a map, it recursively creates a deep copy and merge of those two maps, and uses that value instead.
If not, it keeps the current map and ignores the value from toMerge
(which is, arguably, slightly inconsistent, but for structured JSON data, it'll probably never happen).