Scoop API

scoop:scoop.std:0.1.0

src/comparisons/selectors.scoop

Selected production source · src/comparisons/selectors.scoop

1package scoop.comparisons
3/**
4 * Compares the keys produced by the selector using the supplied or natural key ordering.
5 */
6public fun <T, K : Compare<K>> compareBy(selector: (T) -> K): Comparator<T> =
7 compareBy<T, K>(naturalOrder<K>(), selector)
9/**
10 * Compares the keys produced by the selector using the supplied or natural key ordering.
11 */
12public fun <T, K> compareBy(comparator: Comparator<K>, selector: (T) -> K): Comparator<T> =
13 comparatorOf<T> { left, right ->
14 val leftKey = selector(left)
15 val rightKey = selector(right)
16 comparator.compare(leftKey, rightKey)
17 }
19/**
20 * Uses the additional selected-key comparison only when the original comparator reports equality.
21 */
22public fun <T, K : Compare<K>> Comparator<T>.thenBy(selector: (T) -> K): Comparator<T> =
23 thenBy<T, K>(naturalOrder<K>(), selector)
25/**
26 * Uses the additional selected-key comparison only when the original comparator reports equality.
27 */
28public fun <T, K> Comparator<T>.thenBy(
29 comparator: Comparator<K>, selector: (T) -> K
30): Comparator<T> {
31 val primary = this
32 return comparatorOf<T> { left, right ->
33 val result = primary.compare(left, right)
34 if (result != 0L) return@comparatorOf result
35 val leftKey = selector(left)
36 val rightKey = selector(right)
37 comparator.compare(leftKey, rightKey)
38 }