2019-10-07 23:19:48 +02:00
package moe.kageru.sekwences
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
2019-10-09 12:01:53 +02:00
class CoalesceTest : ShouldSpec ( {
2019-10-07 23:19:48 +02:00
" should merge numbers " {
val input = sequenceOf ( 1 , 2 , 3 , 4 , 5 , 6 , 4 )
val output = input . coalesce { first , second ->
val sum = first + second
if ( sum <= 10 ) sum else null
} . toList ( )
output shouldBe listOf ( 10 , 5 , 10 )
}
" should merge collections " {
val input = sequenceOf ( " apple " , " apricot " , " banana " , " peach " , " pear " , " plum " )
val output = input . map { listOf ( it ) } . coalesce { first , second ->
if ( first . first ( ) [ 0 ] == second . first ( ) [ 0 ] ) {
first + second
} else {
null
}
} . toList ( )
output shouldBe listOf ( listOf ( " apple " , " apricot " ) , listOf ( " banana " ) , listOf ( " peach " , " pear " , " plum " ) )
}
" should handle empty sequences " {
val input = emptySequence < Int > ( )
val output = input . coalesce { _ , _ -> 0 }
output shouldBe emptySequence ( )
}
" should handle single elements " {
val input = sequenceOf ( 1 )
val output = input . coalesce { a , b -> if ( a > 5 ) a else b } . toList ( )
output shouldBe listOf ( 1 )
}
" should not modify sequences that can’t be merged " {
val input = listOf ( 6 , 7 , 34 , 8 )
val output = input . asSequence ( ) . coalesce { first , second ->
val sum = first + second
if ( sum <= 10 ) sum else null
} . toList ( )
output shouldBe input
}
2019-10-07 23:25:23 +02:00
} )