Introduce reversed extension for Comparator.
This commit is contained in:
@@ -315,4 +315,15 @@ public fun <T: Comparable<T>> nullsLast(): Comparator<T?> {
|
||||
return a.compareTo(b)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns a comparator that imposes the reverse ordering of this comparator. */
|
||||
public fun <T> Comparator<T>.reversed(): Comparator<T> = when (this) {
|
||||
is ReversedComparator -> this.comparator
|
||||
else -> ReversedComparator(this)
|
||||
}
|
||||
|
||||
|
||||
private class ReversedComparator<T>(public val comparator: Comparator<T>): Comparator<T> {
|
||||
override fun compare(a: T, b: T): Int = comparator.compare(b, a)
|
||||
}
|
||||
|
||||
@@ -589,7 +589,12 @@ class CollectionTest {
|
||||
}
|
||||
|
||||
test fun sortedWith() {
|
||||
expect(listOf("BAD", "dad", "cat")) { listOf("cat", "dad", "BAD").sortedWith(compareBy { it.toUpperCase().reverse() }) }
|
||||
val comparator = compareBy<String> { it.toUpperCase().reverse() }
|
||||
val data = listOf("cat", "dad", "BAD")
|
||||
|
||||
expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator) }
|
||||
expect(listOf("cat", "dad", "BAD")) { data.sortedWith(comparator.reversed()) }
|
||||
expect(listOf("BAD", "dad", "cat")) { data.sortedWith(comparator.reversed().reversed()) }
|
||||
}
|
||||
|
||||
test fun decomposeFirst() {
|
||||
|
||||
Reference in New Issue
Block a user