diff --git a/lib/src/extension/map_extensions_mixin.dart b/lib/src/extension/map_extensions_mixin.dart index f3e9d3b5..c36f29b9 100644 --- a/lib/src/extension/map_extensions_mixin.dart +++ b/lib/src/extension/map_extensions_mixin.dart @@ -40,6 +40,17 @@ abstract class KMapExtensionsMixin implements KMapExtension, KMap it.key, transform); } + @override + KMap toMap() { + if (size == 0) return emptyMap(); + return toMutableMap(); + } + + @override + KMutableMap toMutableMap() { + return mutableMapOf(map); + } + @override String toString() { return entries.joinToString(separator: ", ", prefix: "{", postfix: "}", transform: (it) => _entryToString(it)); diff --git a/lib/src/k_map.dart b/lib/src/k_map.dart index eb73ab3f..ddd251a2 100644 --- a/lib/src/k_map.dart +++ b/lib/src/k_map.dart @@ -156,5 +156,17 @@ abstract class KMapExtension { */ M mapValuesTo>(M destination, R Function(KMapEntry entry) transform); -// TODO toMutableMap + /** + * Returns a new read-only map containing all key-value pairs from the original map. + * + * The returned map preserves the entry iteration order of the original map. + */ + KMap toMap(); + + /** + * Returns a new mutable map containing all key-value pairs from the original map. + * + * The returned map preserves the entry iteration order of the original map. + */ + KMutableMap toMutableMap(); } diff --git a/lib/src/k_map_mutable.dart b/lib/src/k_map_mutable.dart index ada5fcc0..f5c2e338 100644 --- a/lib/src/k_map_mutable.dart +++ b/lib/src/k_map_mutable.dart @@ -101,7 +101,6 @@ abstract class KMutableMapExtension { */ void putAllPairs(KIterable> pairs); - // TODO toMap /** * If the specified key is not already associated with a value (or is mapped to `null`) associates it with the given value and returns `null`, else returns the current value. * diff --git a/test/collection/map_extensions_test.dart b/test/collection/map_extensions_test.dart index 652fd68f..c4b21f2c 100644 --- a/test/collection/map_extensions_test.dart +++ b/test/collection/map_extensions_test.dart @@ -59,4 +59,38 @@ void main() { expect(mapped.size, 2); }); }); + + group("toMap", () { + test("makes a copy which doesn't share memory", () { + final map = mutableMapOf({ + 1: "Bulbasaur", + 2: "Ivysaur", + }); + final copy = map.toMap(); + expect(copy, map); + map.put(3, "Venusaur"); + expect(map.size, 3); + expect(copy.size, 2); + }); + + test("make a copy of an empty list", () { + final map = emptyMap(); + final copy = map.toMap(); + expect(copy, map); + }); + }); + + group("toMutableMap", () { + test("makes a copy", () { + var map = mapOf({ + 1: "Bulbasaur", + 2: "Ivysaur", + }); + final copy = map.toMutableMap(); + expect(map, copy); + copy.put(3, "Venusaur"); + expect(copy.size, 3); + expect(map.size, 2); + }); + }); }