standard library: 'maxBy' and 'minBy' functions added (#KT-4267 fixed)

This commit is contained in:
nik
2013-11-30 00:22:40 +04:00
committed by Evgeny Gerashchenko
parent 45e9211943
commit ac6dc9fa54
16 changed files with 654 additions and 0 deletions
@@ -140,5 +140,93 @@ fun iterables(): ArrayList<GenericFunction> {
}
}
templates add f("minBy(f: (T) -> R)") {
doc = "Returns the first element yielding the smallest value of the given function or null if there are no elements"
typeParam("R: Comparable<R>")
typeParam("T: Any")
returns("T?")
Iterables.body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = f(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
"""
}
listOf(Arrays, PrimitiveArrays).forEach {
it.body {
"""
if (size == 0) return null
var minElem = this[0]
var minValue = f(minElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
"""
}
}
}
templates add f("maxBy(f: (T) -> R)") {
doc = "Returns the first element yielding the largest value of the given function or null if there are no elements"
typeParam("R: Comparable<R>")
typeParam("T: Any")
returns("T?")
Iterables.body {
"""
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = f(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
"""
}
listOf(Arrays, PrimitiveArrays).forEach {
it.body {
"""
if (isEmpty()) return null
var maxElem = this[0]
var maxValue = f(maxElem)
for (i in 1..lastIndex) {
val e = this[i]
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
"""
}
}
}
return templates
}
@@ -122,5 +122,53 @@ fun iterators(): List<GenericFunction> {
}
}
templates add f("minBy(f: (T) -> R)") {
doc = "Returns the first element yielding the smallest value of the given function or null if there are no elements"
typeParam("R: Comparable<R>")
typeParam("T: Any")
returns("T?")
body {
"""
if (!hasNext()) return null
var minElem = next()
var minValue = f(minElem)
while (hasNext()) {
val e = next()
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
"""
}
}
templates add f("maxBy(f: (T) -> R)") {
doc = "Returns the first element yielding the largest value of the given function or null if there are no elements"
typeParam("R: Comparable<R>")
typeParam("T: Any")
returns("T?")
body {
"""
if (!hasNext()) return null
var maxElem = next()
var maxValue = f(maxElem)
while (hasNext()) {
val e = next()
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
"""
}
}
return templates.sort()
}