Skip to content

Commit 112fb4d

Browse files
authored
CanonicalizedMap: added constructor fromEntries. (dart-archive/collection#347)
1 parent f0785c9 commit 112fb4d

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

pkgs/collection/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- Shuffle `IterableExtension.sample` results.
55
- Fix `mergeSort` when the runtime iterable generic is a subtype of the static
66
generic.
7+
- `CanonicalizedMap`: added constructor `fromEntries`.
78
- Require Dart `^3.1.0`
89
- Mark "mixin" classes as `mixin`.
910

pkgs/collection/lib/src/canonicalized_map.dart

+17
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,23 @@ class CanonicalizedMap<C, K, V> implements Map<K, V> {
4646
addAll(other);
4747
}
4848

49+
/// Creates a canonicalized map that is initialized with the key/value pairs
50+
/// of [entries].
51+
///
52+
/// The [canonicalize] function should return the canonical value for the
53+
/// given key. Keys with the same canonical value are considered equivalent.
54+
///
55+
/// The [isValidKey] function is called before calling [canonicalize] for
56+
/// methods that take arbitrary objects. It can be used to filter out keys
57+
/// that can't be canonicalized.
58+
CanonicalizedMap.fromEntries(
59+
Iterable<MapEntry<K, V>> entries, C Function(K key) canonicalize,
60+
{bool Function(K key)? isValidKey})
61+
: _canonicalize = canonicalize,
62+
_isValidKeyFn = isValidKey {
63+
addEntries(entries);
64+
}
65+
4966
CanonicalizedMap._(
5067
this._canonicalize, this._isValidKeyFn, Map<C, MapEntry<K, V>> base) {
5168
_base.addAll(base);

pkgs/collection/test/canonicalized_map_test.dart

+18
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,24 @@ void main() {
205205
});
206206
});
207207

208+
group('CanonicalizedMap.fromEntries', () {
209+
test('canonicalizes its keys', () {
210+
var map = CanonicalizedMap.fromEntries(
211+
{'1': 'value 1', '2': 'value 2', '3': 'value 3'}.entries, int.parse);
212+
expect(map['01'], equals('value 1'));
213+
expect(map['02'], equals('value 2'));
214+
expect(map['03'], equals('value 3'));
215+
});
216+
217+
test('uses the final value for collisions', () {
218+
var map = CanonicalizedMap.fromEntries(
219+
{'1': 'value 1', '01': 'value 2', '001': 'value 3'}.entries,
220+
int.parse);
221+
expect(map.length, equals(1));
222+
expect(map['0001'], equals('value 3'));
223+
});
224+
});
225+
208226
group('CanonicalizedMap.toMapOfCanonicalKeys', () {
209227
test('convert to a `Map<C,V>`', () {
210228
var map = CanonicalizedMap.from(

0 commit comments

Comments
 (0)