Added max() and min() for CharArrays.

This commit is contained in:
Evgeny Gerashchenko
2013-12-06 20:35:31 +04:00
parent f439604b57
commit e80af77c31
3 changed files with 32 additions and 2 deletions
@@ -225,6 +225,20 @@ public inline fun <R, C: MutableCollection<in R>> CharArray.mapTo(result: C, tra
return result
}
/**
* Returns the largest element or null if there are no elements
*/
public fun CharArray.max() : Char? {
if (isEmpty()) return null
var max = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
@@ -244,6 +258,20 @@ public inline fun <R: Comparable<R>> CharArray.maxBy(f: (Char) -> R) : Char? {
return maxElem
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun CharArray.min() : Char? {
if (isEmpty()) return null
var min = this[0]
for (i in 1..lastIndex) {
val e = this[i]
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
+2
View File
@@ -92,6 +92,7 @@ class ArraysJVMTest {
expect(2, { shortArray(3, 2).min() })
expect(2.0.toFloat(), { floatArray(3.0.toFloat(), 2.0.toFloat()).min() })
expect(2.0, { doubleArray(2.0, 3.0).min() })
expect('a', { charArray('a', 'b').min() })
}
test fun max() {
@@ -103,6 +104,7 @@ class ArraysJVMTest {
expect(3, { shortArray(3, 2).max() })
expect(3.0.toFloat(), { floatArray(3.0.toFloat(), 2.0.toFloat()).max() })
expect(3.0, { doubleArray(2.0, 3.0).max() })
expect('b', { charArray('a', 'b').max() })
}
test fun minBy() {
@@ -149,7 +149,7 @@ fun iterables(): ArrayList<GenericFunction> {
templates add f("min()") {
doc = "Returns the smallest element or null if there are no elements"
returns("T?")
absentFor(PrimitiveType.Boolean, PrimitiveType.Char)//currently there are no sane way to compare Char? with something (KT-4251)
absentFor(PrimitiveType.Boolean)
typeParam("T: Comparable<T>")
isInline = false
Iterables.body {
@@ -184,7 +184,7 @@ fun iterables(): ArrayList<GenericFunction> {
templates add f("max()") {
doc = "Returns the largest element or null if there are no elements"
returns("T?")
absentFor(PrimitiveType.Boolean, PrimitiveType.Char)//currently there are no sane way to compare Char? with something (KT-4251)
absentFor(PrimitiveType.Boolean)
typeParam("T: Comparable<T>")
isInline = false
Iterables.body {