Skip to content

Commit

Permalink
Introduce a new lastBy() 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 May 27, 2022
1 parent 69766da commit 22c3c5e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
@@ -1,5 +1,9 @@
## 1.16.1-dev

* Add a top-level `lastBy()` function that converts an `Iterable` to a `Map` by
grouping its elements using a function, keeping the last element for each
computed key.

## 1.16.0

* Add an `Iterable.slices` extension method.
Expand Down
13 changes: 13 additions & 0 deletions lib/src/functions.dart
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> lastBy<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
Expand Up @@ -79,6 +79,23 @@ void main() {
});
});

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

test("keeps the latest element for the function's return value", () {
expect(
lastBy(['foo', 'bar', 'baz', 'bop', 'qux'],
(String 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 22c3c5e

Please sign in to comment.