/
Comparator.ts
54 lines (46 loc) · 1.64 KB
/
Comparator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
interface Comparator<T> {
(a: T, b: T): number;
reversed(): Comparator<T>;
then(compare: (a: T, b: T) => number): Comparator<T>;
thenDescending(compare: (a: T, b: T) => number): Comparator<T>;
thenBy(selector: (value: T) => any): Comparator<T>;
thenByDescending(selector: (value: T) => any): Comparator<T>;
}
export default Comparator;
const naturalOrder = (a, b) => a < b ? -1 : a > b ? 1 : 0;
export function compare<T>(comparison: (a: T, b: T) => number): Comparator<T> {
return Object.assign(comparison, {
reversed(): Comparator<T> {
return compare(
(a: T, b: T) => comparison(a, b) * -1
);
},
then(nextComparison: (a: T, b: T) => number): Comparator<T> {
return compare(
(a: T, b: T) => {
const result = comparison(a, b);
return result !== 0
? result
: nextComparison(a, b);
}
);
},
thenDescending(nextComparison: (a: T, b: T) => number): Comparator<T> {
return this.then(
compare(nextComparison)
.reversed()
);
},
thenBy(selector: (value: T) => any): Comparator<T> {
return this.then(
(a: T, b: T) => naturalOrder(selector(a), selector(b))
);
},
thenByDescending(selector: (value: T) => any): Comparator<T> {
return this.then(
compare((a: T, b: T) => naturalOrder(selector(a), selector(b)))
.reversed()
);
}
});
}