Last active
October 28, 2022 11:22
-
-
Save martinky/1291567276d2161896dbb726d8e5774f to your computer and use it in GitHub Desktop.
Kotlin extension function to produce an interleaved flattened list from a collection of iterables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Produces a flattened [List] that is an interleaved merge of the input iterables. | |
* | |
* For example: | |
* | |
* ``` | |
* listOf( | |
* listOf(1, 2, 3, 4), | |
* listOf('a', 'b') | |
* ).interleave() | |
* ``` | |
* | |
* will produce this list: | |
* | |
* ``` | |
* [1, 'a', 2, 'b', 3, 4] | |
* ``` | |
*/ | |
fun <T> Iterable<Iterable<T>>.interleave(): List<T> { | |
val result = ArrayList<T>() | |
val iterators = this.map { it.iterator() } | |
do { | |
var hasMore = false | |
for (i in iterators) { | |
if (i.hasNext()) { | |
result.add(i.next()) | |
hasMore = true | |
} | |
} | |
} while (hasMore) | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment