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

Commit

Permalink
CanonicalizedMap: added constructor fromEntries. (#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
gmpassos authored Jun 7, 2024
1 parent 586a5e8 commit 141d83a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
- Shuffle `IterableExtension.sample` results.
- Fix `mergeSort` when the runtime iterable generic is a subtype of the static
generic.
- `CanonicalizedMap`: added constructor `fromEntries`.
- Require Dart `^3.1.0`
- Mark "mixin" classes as `mixin`.

Expand Down
17 changes: 17 additions & 0 deletions lib/src/canonicalized_map.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ class CanonicalizedMap<C, K, V> implements Map<K, V> {
addAll(other);
}

/// Creates a canonicalized map that is initialized with the key/value pairs
/// of [entries].
///
/// The [canonicalize] function should return the canonical value for the
/// given key. Keys with the same canonical value are considered equivalent.
///
/// The [isValidKey] function is called before calling [canonicalize] for
/// methods that take arbitrary objects. It can be used to filter out keys
/// that can't be canonicalized.
CanonicalizedMap.fromEntries(
Iterable<MapEntry<K, V>> entries, C Function(K key) canonicalize,
{bool Function(K key)? isValidKey})
: _canonicalize = canonicalize,
_isValidKeyFn = isValidKey {
addEntries(entries);
}

CanonicalizedMap._(
this._canonicalize, this._isValidKeyFn, Map<C, MapEntry<K, V>> base) {
_base.addAll(base);
Expand Down
18 changes: 18 additions & 0 deletions test/canonicalized_map_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,24 @@ void main() {
});
});

group('CanonicalizedMap.fromEntries', () {
test('canonicalizes its keys', () {
var map = CanonicalizedMap.fromEntries(
{'1': 'value 1', '2': 'value 2', '3': 'value 3'}.entries, int.parse);
expect(map['01'], equals('value 1'));
expect(map['02'], equals('value 2'));
expect(map['03'], equals('value 3'));
});

test('uses the final value for collisions', () {
var map = CanonicalizedMap.fromEntries(
{'1': 'value 1', '01': 'value 2', '001': 'value 3'}.entries,
int.parse);
expect(map.length, equals(1));
expect(map['0001'], equals('value 3'));
});
});

group('CanonicalizedMap.toMapOfCanonicalKeys', () {
test('convert to a `Map<C,V>`', () {
var map = CanonicalizedMap.from(
Expand Down

0 comments on commit 141d83a

Please sign in to comment.