Provide flatMapIndexed operation

- similar to flatMap, but transform function takes index and element

#KT-36894
This commit is contained in:
Ilya Gorbunov
2020-06-19 16:16:55 +03:00
parent db93462bcf
commit 130987fa1e
20 changed files with 1216 additions and 74 deletions
@@ -785,6 +785,39 @@ public inline fun <R> CharSequence.flatMap(transform: (Char) -> Iterable<R>): Li
return flatMapTo(ArrayList<R>(), transform)
}
/**
* Returns a single list of all elements yielded from results of [transform] function being invoked on each character
* and its index in the original char sequence.
*
* @sample samples.collections.Collections.Transformations.flatMapIndexed
*/
@SinceKotlin("1.4")
@OptIn(kotlin.experimental.ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
@kotlin.jvm.JvmName("flatMapIndexedIterable")
@kotlin.internal.InlineOnly
public inline fun <R> CharSequence.flatMapIndexed(transform: (index: Int, Char) -> Iterable<R>): List<R> {
return flatMapIndexedTo(ArrayList<R>(), transform)
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each character
* and its index in the original char sequence, to the given [destination].
*/
@SinceKotlin("1.4")
@OptIn(kotlin.experimental.ExperimentalTypeInference::class)
@OverloadResolutionByLambdaReturnType
@kotlin.jvm.JvmName("flatMapIndexedIterableTo")
@kotlin.internal.InlineOnly
public inline fun <R, C : MutableCollection<in R>> CharSequence.flatMapIndexedTo(destination: C, transform: (index: Int, Char) -> Iterable<R>): C {
var index = 0
for (element in this) {
val list = transform(index++, element)
destination.addAll(list)
}
return destination
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each character of original char sequence, to the given [destination].
*/