KT-33761 Add reduceOrNull

This commit is contained in:
Alfredo Delli Bovi
2019-12-11 08:31:18 +01:00
committed by Ilya Gorbunov
parent 39e1b24c2c
commit f5d696d3c4
10 changed files with 345 additions and 0 deletions
@@ -1195,6 +1195,21 @@ public inline fun CharSequence.reduceIndexed(operation: (index: Int, acc: Char,
return accumulator
}
/**
* Accumulates value starting with the first character and applying [operation] from left to right to current accumulator value and each character. Returns null if the char sequence is empty.
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
public inline fun CharSequence.reduceOrNull(operation: (acc: Char, Char) -> Char): Char? {
if (isEmpty())
return null
var accumulator = this[0]
for (index in 1..lastIndex) {
accumulator = operation(accumulator, this[index])
}
return accumulator
}
/**
* Accumulates value starting with last character and applying [operation] from right to left to each character and current accumulator value.
*/