Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce minOf() on KtIterable #171

Merged
merged 4 commits into from
Oct 14, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/src/collection/kt_iterable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,24 @@ extension KtIterableExtensions<T> on KtIterable<T> {
return minElement;
}

/// Returns the smallest value among all values produced by selector function applied to each element in the array.
///
/// Throws a [NoSuchElementException] if the list is empty.
R minOf<R extends Comparable>(R Function(T) selector) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the selector be optional?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no, kotlins selector is required, too

final i = iterator();
if (!i.hasNext()) {
throw const NoSuchElementException("Collection is empty.");
}
R minValue = selector(i.next());
while (i.hasNext()) {
final v = selector(i.next());
if (minValue.compareTo(v) > 0) {
minValue = v;
}
}
return minValue;
}

/// Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
T? minWith(Comparator<T> comparator) {
final i = iterator();
Expand Down
19 changes: 19 additions & 0 deletions test/collection/iterable_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,25 @@ void testIterable(KtIterable<T> Function<T>() emptyIterable,
});
});

group("minOf", () {
test("gets min value", () {
const comparableItem = Duration(seconds: 1);
final iterable = iterableOf(const [
Duration(seconds: 3),
Duration(seconds: 2),
comparableItem,
]);
expect(iterable.minOf((it) => it), comparableItem);
});

test("empty iterable throw ", () {
final iterable = emptyIterable<int>();
expect(() => iterable.minOf((it) => it), throwsException);
// with generic type
expect(() => iterable.minOf<num>((it) => it), throwsException);
});
});

group("minWith", () {
int _intComparison(int value, int other) => value.compareTo(other);

Expand Down