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

Commit

Permalink
Add an extension lastBy on Iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
Kernald committed May 30, 2022
1 parent 22c3c5e commit afe0ad0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/src/iterable_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import 'dart:math' show Random;
import 'package:collection/src/utils.dart';

import 'algorithms.dart';
import 'functions.dart' as functions;

/// Extensions that apply to all iterables.
///
Expand Down Expand Up @@ -353,6 +354,12 @@ extension IterableExtension<T> on Iterable<T> {
return null;
}

/// Associates the elements in [this] 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<K, T> lastBy<K>(K Function(T) key) => functions.lastBy(this, key);

/// Groups elements by [keyOf] then folds the elements in each group.
///
/// A key is found for each element using [keyOf].
Expand Down
19 changes: 19 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,25 @@ void main() {
expect(iterable([1, 3, 5]).singleOrNull, null);
});
});
group('.lastBy', () {
test('empty', () {
expect(iterable([]).lastBy((dynamic _) {}), {});
});
test('single', () {
expect(iterable([1]).lastBy(toString), {
'1': 1,
});
});
test('multiple', () {
expect(
iterable([1, 2, 3, 4, 5]).lastBy((x) => x.isEven),
{
false: 5,
true: 4,
},
);
});
});
group('.groupFoldBy', () {
test('empty', () {
expect(iterable([]).groupFoldBy(unreachable, unreachable), {});
Expand Down

0 comments on commit afe0ad0

Please sign in to comment.