diff --git a/lib/src/iterable_extensions.dart b/lib/src/iterable_extensions.dart index ac82112..88f320d 100644 --- a/lib/src/iterable_extensions.dart +++ b/lib/src/iterable_extensions.dart @@ -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. /// @@ -353,6 +354,12 @@ extension IterableExtension on Iterable { 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 lastBy(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]. diff --git a/test/extensions_test.dart b/test/extensions_test.dart index 1ccebde..ce4b2e9 100644 --- a/test/extensions_test.dart +++ b/test/extensions_test.dart @@ -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), {});