mergeAttributes: deepcopy RHS Map if LHS isn't Map (#23)

mergeAttributes: deepcopy RHS Map if LHS isn't Map
This commit is contained in:
Artem Sheremet
2018-10-09 17:59:02 +02:00
committed by Yegor
parent 856e6f2a7a
commit 044e4c1f43
2 changed files with 26 additions and 2 deletions

View File

@ -12,8 +12,13 @@ void mergeAttributes(Map<String, dynamic> attributes,
{@required Map<String, dynamic> into}) {
assert(attributes != null && into != null);
attributes.forEach((String name, dynamic value) {
final dynamic targetValue = into[name];
if (value is Map && targetValue is Map) {
dynamic targetValue = into[name];
if (value is Map) {
if (targetValue is! Map) {
// Let mergeAttributes make a deep copy, because assigning a reference
// of 'value' will expose 'value' to be mutated by further merges.
into[name] = targetValue = <String, dynamic>{};
}
mergeAttributes(value, into: targetValue);
} else {
into[name] = value;

View File

@ -35,6 +35,25 @@ void main() {
},
});
});
test('does not allow overriding original maps', () {
final environment = <String, dynamic>{
'extra': {
'device': 'Pixel 2',
},
};
final event = <String, dynamic>{
'extra': {
'widget': 'Scaffold',
},
};
final target = <String, dynamic>{};
mergeAttributes(environment, into: target);
mergeAttributes(event, into: target);
expect(environment['extra'], {'device': 'Pixel 2'});
});
});
group('formatDateAsIso8601WithSecondPrecision', () {