KT-33761 Add reduceOrNull
This commit is contained in:
committed by
Ilya Gorbunov
parent
39e1b24c2c
commit
f5d696d3c4
@@ -1006,6 +1006,20 @@ class ArraysTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun reduceOrNull() {
|
||||
expect(-4) { intArrayOf(1, 2, 3).reduceOrNull { a, b -> a - b } }
|
||||
expect(-4.toLong()) { longArrayOf(1, 2, 3).reduceOrNull { a, b -> a - b } }
|
||||
expect(-4F) { floatArrayOf(1F, 2F, 3F).reduceOrNull { a, b -> a - b } }
|
||||
expect(-4.0) { doubleArrayOf(1.0, 2.0, 3.0).reduceOrNull { a, b -> a - b } }
|
||||
expect('3') { charArrayOf('1', '3', '2').reduceOrNull { a, b -> if (a > b) a else b } }
|
||||
expect(false) { booleanArrayOf(true, true, false).reduceOrNull { a, b -> a && b } }
|
||||
expect(true) { booleanArrayOf(true, true).reduceOrNull { a, b -> a && b } }
|
||||
expect(0.toByte()) { byteArrayOf(3, 2, 1).reduceOrNull { a, b -> (a - b).toByte() } }
|
||||
expect(0.toShort()) { shortArrayOf(3, 2, 1).reduceOrNull { a, b -> (a - b).toShort() } }
|
||||
|
||||
expect(null, { intArrayOf().reduceOrNull { a, b -> a + b } })
|
||||
}
|
||||
|
||||
@Test fun reduceRight() {
|
||||
expect(2) { intArrayOf(1, 2, 3).reduceRight { a, b -> a - b } }
|
||||
expect(2.toLong()) { longArrayOf(1, 2, 3).reduceRight { a, b -> a - b } }
|
||||
|
||||
@@ -315,6 +315,15 @@ class CollectionTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun reduceOrNull() {
|
||||
expect("1234") {
|
||||
val list = listOf("1", "2", "3", "4")
|
||||
list.reduceOrNull { a, b -> a + b }
|
||||
}
|
||||
|
||||
expect(null, { arrayListOf<Int>().reduceOrNull { a, b -> a + b } })
|
||||
}
|
||||
|
||||
@Test fun reduceRight() {
|
||||
expect("1234") {
|
||||
val list = listOf("1", "2", "3", "4")
|
||||
|
||||
@@ -379,6 +379,10 @@ public class SequenceTest {
|
||||
assertEquals(expected_, b.toList())
|
||||
}
|
||||
|
||||
@Test fun reduceOrNullOnEmpty() {
|
||||
expect(null, { sequenceOf<Int>().reduceOrNull { acc, i -> acc + i } })
|
||||
}
|
||||
|
||||
@Test fun minusElement() = testMinus(expected = listOf("foo", "bar")) { it - "bar" - "zoo" }
|
||||
@Test fun minusCollection() = testMinus { it - listOf("bar", "zoo") }
|
||||
@Test fun minusArray() = testMinus { it - arrayOf("bar", "zoo") }
|
||||
|
||||
@@ -1281,6 +1281,13 @@ class StringTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun reduceOrNull() = withOneCharSequenceArg { arg1 ->
|
||||
// get the smallest character(by char value)
|
||||
assertEquals('a', arg1("bacfd").reduceOrNull { v, c -> if (v > c) c else v })
|
||||
|
||||
expect(null, { arg1("").reduceOrNull { _, _ -> '\n' } })
|
||||
}
|
||||
|
||||
@Test fun groupBy() = withOneCharSequenceArg("abAbaABcD") { data ->
|
||||
// group characters by their case
|
||||
val result = data.groupBy { it.isAsciiUpperCase() }
|
||||
|
||||
Reference in New Issue
Block a user