diff --git a/CHANGELOG.md b/CHANGELOG.md index e92a5d2..a6e393f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ * Require Dart 3.0. * Mark mixin classes as `mixin class`. +* Added a `Map.pairs` extension method to make it easier to work with maps using + Dart 3 record types. ## 1.17.2 diff --git a/lib/collection.dart b/lib/collection.dart index f6f4ae3..560eb55 100644 --- a/lib/collection.dart +++ b/lib/collection.dart @@ -17,6 +17,7 @@ export 'src/functions.dart'; export 'src/iterable_extensions.dart'; export 'src/iterable_zip.dart'; export 'src/list_extensions.dart'; +export 'src/map_extensions.dart'; export 'src/priority_queue.dart'; export 'src/queue_list.dart'; export 'src/union_set.dart'; diff --git a/lib/src/functions.dart b/lib/src/functions.dart index 8f60b26..4b6a8d5 100644 --- a/lib/src/functions.dart +++ b/lib/src/functions.dart @@ -5,6 +5,7 @@ import 'dart:collection'; import 'dart:math' as math; +import 'map_extensions.dart'; import 'utils.dart'; /// Creates a new map from [map] with new keys and values. diff --git a/lib/src/map_extensions.dart b/lib/src/map_extensions.dart new file mode 100644 index 0000000..e5d6b5a --- /dev/null +++ b/lib/src/map_extensions.dart @@ -0,0 +1,8 @@ +// Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +extension MapExtensions on Map { + /// Like [Map.entries], but returns each entry as a record. + Iterable<(K, V)> get pairs => entries.map((e) => (e.key, e.value)); +} diff --git a/test/extensions_test.dart b/test/extensions_test.dart index 31bb458..4053d8f 100644 --- a/test/extensions_test.dart +++ b/test/extensions_test.dart @@ -1900,6 +1900,23 @@ void main() { }); }); }); + + group('Map', () { + group('pairs', () { + test('empty map', () { + expect({}.pairs, isEmpty); + }); + + test('single pair', () { + expect({1: 2}.pairs, equals([(1, 2)])); + }); + + test('multiple pairs', () { + expect({1: 2, 3: 4, 5: 6}.pairs, + equals([(1, 2), (3, 4), (5, 6)])); + }); + }); + }); } /// Creates a plain iterable not implementing any other class.