Add flatten, flatMap, and filterNotNull functions with corresponding tests
This commit is contained in:
parent
357585d3ba
commit
3b6504d3b1
@ -91,4 +91,19 @@ class StdlibTest {
|
|||||||
assertEquals([1,2], (1..8).dropLast(6).toList() )
|
assertEquals([1,2], (1..8).dropLast(6).toList() )
|
||||||
""".trimIndent())
|
""".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() )
|
||||||
|
""")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@ -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. */
|
/* Skip the first N elements of this iterable. */
|
||||||
fun Iterable.drop(n) {
|
fun Iterable.drop(n) {
|
||||||
var cnt = 0
|
var cnt = 0
|
||||||
@ -179,6 +187,26 @@ fun Iterable.shuffled() {
|
|||||||
toList().apply { shuffle() }
|
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]. */
|
/* Return string representation like [a,b,c]. */
|
||||||
fun List.toString() {
|
fun List.toString() {
|
||||||
"[" + joinToString(",") + "]"
|
"[" + joinToString(",") + "]"
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user