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

Commit

Permalink
Introduce a new associateBy() function
Browse files Browse the repository at this point in the history
Similar to groupBy(), except that it only keeps the latest value
corresponding to a given key.

Prior art: [Kotlin](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/associate-by.html)
  • Loading branch information
Kernald committed Oct 25, 2021
1 parent 71fb216 commit b5cf809
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
Assignment to `Equality` with a nullable type is still allowed because of
covariance. The `equals` and `hash` methods continue to accept nullable
arguments.
* Add a top-level `associateBy()` function that converts an `Iterable` to a
`Map` by grouping its elements using a function, keeping the last element
for each computed key.


## 1.15.0
Expand Down
13 changes: 13 additions & 0 deletions lib/src/functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ Map<K, V> mergeMaps<K, V>(Map<K, V> map1, Map<K, V> map2,
return result;
}

/// Associates the elements in [values] by the value returned by [key].
///
/// Returns a map from keys computed by [key] to the last value for which [key]
/// returns that key.
Map<T, S> associateBy<S, T>(Iterable<S> values, T Function(S) key) {
var map = <T, S>{};
for (var element in values) {
map[key(element)] = element;
}

return map;
}

/// Groups the elements in [values] by the value returned by [key].
///
/// Returns a map from keys computed by [key] to a list of all values for which
Expand Down
17 changes: 17 additions & 0 deletions test/functions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,23 @@ void main() {
});
});

group('associateBy()', () {
test('returns an empty map for an empty iterable', () {
expect(associateBy([], expectAsync1((dynamic _) {}, count: 0)), isEmpty);
});

test("keeps the latest element for the function's return value", () {
expect(
associateBy(['foo', 'bar', 'baz', 'bop', 'qux'],
(dynamic string) => string[1]),
equals({
'o': 'bop',
'a': 'baz',
'u': 'qux',
}));
});
});

group('groupBy()', () {
test('returns an empty map for an empty iterable', () {
expect(groupBy([], expectAsync1((dynamic _) {}, count: 0)), isEmpty);
Expand Down

0 comments on commit b5cf809

Please sign in to comment.