Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Add extension methods for converting between maps and records #289

Merged
merged 2 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions lib/collection.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
1 change: 1 addition & 0 deletions lib/src/functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions lib/src/map_extensions.dart
Original file line number Diff line number Diff line change
@@ -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<K, V> on Map<K, V> {
/// Like [Map.entries], but returns each entry as a record.
Iterable<(K, V)> get pairs => entries.map((e) => (e.key, e.value));
}
17 changes: 17 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1900,6 +1900,23 @@ void main() {
});
});
});

group('Map', () {
group('pairs', () {
test('empty map', () {
expect(<int, int>{}.pairs, isEmpty);
});

test('single pair', () {
expect(<int, int>{1: 2}.pairs, equals([(1, 2)]));
});

test('multiple pairs', () {
expect(<int, int>{1: 2, 3: 4, 5: 6}.pairs,
equals([(1, 2), (3, 4), (5, 6)]));
});
});
});
}

/// Creates a plain iterable not implementing any other class.
Expand Down