Skip to content

Commit

Permalink
add runningReduce()
Browse files Browse the repository at this point in the history
  • Loading branch information
Anas35 committed Oct 16, 2021
1 parent a34fbf4 commit 9024a4f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/src/collection/kt_iterable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1184,6 +1184,21 @@ extension KtIterableExtensions<T> on KtIterable<T> {
return accumulator;
}

/// Returns a list containing successive accumulation values generated by applying [operation] from left to right to each element and current accumulator value that starts with the first element of this collection.
KtList<S> runningReduce<S>(S Function(S acc, T) operation) {
final i = iterator();
if (!i.hasNext()) {
return emptyList();
}
S accumulator = i.next() as S;
final result = mutableListOf<S>()..add(accumulator);
while (i.hasNext()) {
accumulator = operation(accumulator, i.next());
result.add(accumulator);
}
return result;
}

/// Returns a list with elements in reversed order.
KtList<T> reversed() {
if (this is KtCollection && (this as KtCollection).size <= 1) {
Expand Down
14 changes: 14 additions & 0 deletions test/collection/iterable_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1764,6 +1764,20 @@ void testIterable(KtIterable<T> Function<T>() emptyIterable,
});
});

group("runningReduce", () {
if (ordered) {
test("runningReduce", () {
final result = iterableOf<String>(["a", "b", "c", "d"])
.runningReduce((String acc, it) => acc + it);
expect(result, listOf("a", "ab", "abc", "abcd"));
});
}

test("return empty list when list is empty", () {
expect(emptyIterable<int>().runningReduce((_, __) => "S"), emptyList());
});
});

group("reversed", () {
test("mutliple", () {
final result = iterableOf([1, 2, 3, 4]).reversed();
Expand Down

0 comments on commit 9024a4f

Please sign in to comment.