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

Let sumBy accept num/int/double #138

Merged
merged 1 commit into from
Mar 27, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
13 changes: 5 additions & 8 deletions lib/src/collection/kt_iterable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1291,21 +1291,18 @@ extension KtIterableExtensions<T> on KtIterable<T> {
}

/// Returns the sum of all values produced by [selector] function applied to each element in the collection.
int sumBy(int Function(T) selector) {
int sum = 0;
R sumBy<R extends num>(R Function(T) selector) {
var sum = R == double ? 0.0 : 0;
for (final element in iter) {
sum += selector(element);
}
return sum;
return sum as R;
}

/// Returns the sum of all values produced by [selector] function applied to each element in the collection.
@Deprecated("Use sumBy")
double sumByDouble(double Function(T) selector) {
double sum = 0.0;
for (final element in iter) {
sum += selector(element);
}
return sum;
return sumBy(selector);
}

/// Returns a list containing first [n] elements.
Expand Down
17 changes: 15 additions & 2 deletions test/collection/iterable_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1614,13 +1614,26 @@ void testIterable(KtIterable<T> Function<T>() emptyIterable,
});

group("sumBy", () {
test("double", () {
test("int", () {
expect(iterableOf([1, 2, 3]).sumBy((i) => i * 2), 12);
});

test("factor 1.5", () {
test("double", () {
expect(iterableOf([1, 2, 3]).sumBy((i) => i * 1.5), 9.0);

// ignore: deprecated_member_use_from_same_package
expect(iterableOf([1, 2, 3]).sumByDouble((i) => i * 1.5), 9.0);
});

test("double as num", () {
const num factor = 1.5;
expect(iterableOf([1, 2, 3]).sumBy((i) => i * factor), 9.0);
});

test("double as num", () {
const num factor = 2;
expect(iterableOf([1, 2, 3]).sumBy((i) => i * factor), 12);
});
});

group("take", () {
Expand Down