Add flatten, flatMap, and filterNotNull functions with corresponding tests

This commit is contained in:
Sergey Chernov 2025-12-23 18:06:28 +01:00
parent 357585d3ba
commit 3b6504d3b1
2 changed files with 43 additions and 0 deletions

View File

@ -91,4 +91,19 @@ class StdlibTest {
assertEquals([1,2], (1..8).dropLast(6).toList() )
""".trimIndent())
}
@Test
fun testFlattenAndFilter() = runTest {
eval("""
assertEquals([1,2,3,4,5,6], [1,3,5].map { [it, it+1] }.flatten() )
assertEquals([1,3,5], [null,1,null, 3,5].filterNotNull().toList())
""")
}
@Test
fun testFlatMap() = runTest {
eval("""
assertEquals([1,2,3,4,5,6], [1,3,5].flatMap { [it,it+1] }.toList() )
""")
}
}

View File

@ -27,6 +27,14 @@ fun Iterable.filter(predicate) {
}
}
/*
filter out all null elements from this collection (Iterable); collection of
non-null elements is returned
*/
fun Iterable.filterNotNull() {
filter { it != null }
}
/* Skip the first N elements of this iterable. */
fun Iterable.drop(n) {
var cnt = 0
@ -179,6 +187,26 @@ fun Iterable.shuffled() {
toList().apply { shuffle() }
}
/*
Returns a single list of all elements from all collections in the given collection.
@return List
*/
fun Iterable.flatten() {
val result = []
forEach { i ->
i.forEach { result.add(it) }
}
result
}
/*
Returns a single list of all elements yielded from results of transform function being
invoked on each element of original collection.
*/
fun Iterable.flatMap(transform): List {
map(transform).flatten()
}
/* Return string representation like [a,b,c]. */
fun List.toString() {
"[" + joinToString(",") + "]"