Last active
October 16, 2025 14:29
-
-
Save PlugFox/d651661f465199195edd1c08834b04e8 to your computer and use it in GitHub Desktop.
Deep Copy Map
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
| /* | |
| * Deep copy of Map in Dart. | |
| * https://gist.github.com/PlugFox/d651661f465199195edd1c08834b04e8 | |
| * https://dartpad.dev?id=d651661f465199195edd1c08834b04e8 | |
| * Mike Matiunin <[email protected]>, 16 October 2025 | |
| */ | |
| import 'dart:convert' show JsonEncoder; | |
| extension type const CopyMap<K, V>._(Map<K, V> _source) implements Map<K, V> { | |
| CopyMap(Map<K, V> source, {Object? Function(Object object)? copy}) | |
| : _source = source.isEmpty ? <K, V>{} : _deepCopyMap(source, copy); | |
| static Map<K, V> _deepCopyMap<K, V>(Map<K, V> original, Object? Function(Object object)? copy) => <K, V>{ | |
| for (final MapEntry<K, V>(:key, :value) in original.entries) key: _deepCopyValue(value, copy), | |
| }; | |
| static List<V> _deepCopyList<V>(List<V> original, Object? Function(Object object)? copy) => <V>[ | |
| for (final item in original) _deepCopyValue(item, copy), | |
| ]; | |
| static V _deepCopyValue<V>(V value, Object? Function(Object object)? copy) => switch (value) { | |
| Map() => _deepCopyMap(value, copy) as V, | |
| List() => _deepCopyList(value, copy) as V, | |
| num() when value.isFinite => value, | |
| String() || bool() || Null() => value, | |
| Object() when copy != null => copy(value) as V, | |
| _ => value, | |
| }; | |
| String toJsonString() => const JsonEncoder.withIndent(' ').convert(_source); | |
| } | |
| void main() { | |
| final map = <String, Object?>{ | |
| 'map': {'a': 1, 'b': 2}, | |
| 'empty': <String, Object?>{}, | |
| 'list': [1, 2, 3], | |
| 'nested': [ | |
| {'x': 10, 'y': 20}, | |
| [null, 100, 200, 300], | |
| ], | |
| 'text': 'hello', | |
| 'num': 42, | |
| 'bool': true, | |
| 'infinity': double.infinity, | |
| 'null': null, | |
| 'timestamp': DateTime.now(), | |
| 'custom': Object(), | |
| }; | |
| final copy = CopyMap( | |
| map, | |
| copy: | |
| (object) => switch (object) { | |
| num() when object.isInfinite => '<Infinity>', | |
| DateTime() => object.toUtc().toIso8601String(), | |
| Object obj => '${obj.runtimeType.toString()}{}', | |
| }, | |
| ); | |
| print(copy.toJsonString()); // ignore: avoid_print | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment