Scoop API

scoop:scoop.std:0.1.0

src/comparisons/comparator.scoop

Selected production source · src/comparisons/comparator.scoop

1package scoop.comparisons
3/**
4 * Defines an ordering: negative means the first value precedes the second, zero means equivalent,
5 * and positive means it follows.
6 */
7public interface Comparator<T> {
8 /**
9 * Compares two values according to this ordering; only the sign of the result matters.
10 */
11 public fun compare(left: T, right: T): Long
14internal class FunctionComparator<T> internal constructor(
15 private val comparison: (T, T) -> Long
16) : Comparator<T> {
17 public override fun compare(left: T, right: T): Long = comparison(left, right)
20/**
21 * Wraps the supplied comparison function as a Comparator.
22 */
23public fun <T> comparatorOf(comparison: (T, T) -> Long): Comparator<T> =
24 FunctionComparator<T>(comparison)
26/**
27 * Uses the element type's compareTo operation as an ascending comparator.
28 */
29public fun <T : Compare<T>> naturalOrder(): Comparator<T> =
30 comparatorOf<T> { left, right -> left.compareTo(right) }
32/**
33 * Reverses the element type's natural ordering.
34 */
35public fun <T : Compare<T>> reverseOrder(): Comparator<T> = naturalOrder<T>().reversed()
37/**
38 * Returns a comparator with the opposite ordering, preserving equality.
39 */
40public fun <T> Comparator<T>.reversed(): Comparator<T> {
41 val source = this
42 return comparatorOf<T> { left, right -> source.compare(right, left) }