Skip to content

Commit

Permalink
Add Iterable.flatMapIndexed and Iterable.flatMapIndexedTo
Browse files Browse the repository at this point in the history
  • Loading branch information
passsy committed Oct 31, 2021
1 parent 6ef4aff commit a78cc2e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/src/collection/kt_iterable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,29 @@ extension KtIterableExtensions<T> on KtIterable<T> {
return list;
}

/// Returns a single list of all elements yielded from results of [transform]
/// function being invoked on each element and its index in the original
/// collection.
KtList<R> flatMapIndexed<R>(KtIterable<R> Function(int index, T) transform) {
final list = flatMapIndexedTo(mutableListOf<R>(), transform);
// making a temp variable here, it helps dart to get types right ¯\_(ツ)_/¯
// TODO ping dort-lang/sdk team to check that bug
return list;
}

/// Appends all elements yielded from results of [transform] function being
/// invoked on each element and its index in the original collection, to the
/// given [destination].
C flatMapIndexedTo<R, C extends KtMutableCollection<R>>(
C destination, KtIterable<R> Function(int index, T) transform) {
var index = 0;
for (final element in iter) {
final list = transform(index++, element);
destination.addAll(list);
}
return destination;
}

/// Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
C flatMapTo<R, C extends KtMutableCollection<R>>(
C destination, KtIterable<R> Function(T) transform) {
Expand Down
26 changes: 26 additions & 0 deletions test/collection/iterable_extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,32 @@ void testIterable(KtIterable<T> Function<T>() emptyIterable,
});
});

group("flatMapTo", () {
test("flatMapTo int to string", () {
final result = mutableListOf<int>();
final iterable = iterableOf([1, 2, 3]);
iterable.flatMapTo(result, (it) => iterableOf([it, it + 1, it + 2]));
expect(result, listOf(1, 2, 3, 2, 3, 4, 3, 4, 5));
});
});

group("flatMapIndexed", () {
test("flatMapIndexed int to string", () {
final iterable = iterableOf([1, 2, 3]);
expect(iterable.flatMapIndexed((ix, it) => iterableOf([ix, it])).toList(),
listOf(0, 1, 1, 2, 2, 3));
});
});

group("flatMapIndexedTo", () {
test("flatMapIndexedTo int to string", () {
final result = mutableListOf<int>();
final iterable = iterableOf([1, 2, 3]);
iterable.flatMapIndexedTo(result, (ix, it) => iterableOf([ix, it]));
expect(result, listOf(0, 1, 1, 2, 2, 3));
});
});

group("flatten", () {
test("empty", () {
final KtIterable<KtIterable<int>> nested =
Expand Down

0 comments on commit a78cc2e

Please sign in to comment.