Last active
April 18, 2020 14:34
-
-
Save niusounds/30ba030c084ccd11faaab0bf2ecd81cf to your computer and use it in GitHub Desktop.
Map deep merge in Dart.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Map<String, dynamic> deepMergeMap(Map<String, dynamic> a, Map<String, dynamic> b) { | |
b.forEach((k, v) { | |
if (!a.containsKey(k)) { | |
a[k] = v; | |
} else { | |
// TODO handle List type | |
if (a[k] is Map) { | |
deepMergeMap(a[k], b[k]); | |
} else { | |
a[k] = b[k]; | |
} | |
} | |
}); | |
return a; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:map_merge/map_merge.dart'; | |
import 'package:test/test.dart'; | |
void main() { | |
test('deepMergeMap', () { | |
final Map<String, dynamic> a = { | |
'key1': { | |
'key1-1': 111, | |
'key1-2': 222, | |
}, | |
'key2': { | |
'key2-1': 'hello', | |
}, | |
}; | |
final Map<String, dynamic> b = { | |
'key1': { | |
'key1-2': 123456, | |
}, | |
'key2': { | |
'key2-2': 'world', | |
}, | |
}; | |
final Map<String, dynamic> expected = { | |
'key1': { | |
'key1-1': 111, | |
'key1-2': 123456, | |
}, | |
'key2': { | |
'key2-1': 'hello', | |
'key2-2': 'world', | |
}, | |
}; | |
expect(deepMergeMap(a, b), expected); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fix null key