Introduce reversed extension for Comparator.

This commit is contained in:
Ilya Gorbunov
2015-08-26 16:49:44 +03:00
parent 5a474adf59
commit b8badd59ba
2 changed files with 18 additions and 2 deletions
+12 -1
View File
@@ -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() {