-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathsort-compare.ts
75 lines (64 loc) · 1.93 KB
/
sort-compare.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import semver, { coerce } from "semver";
export enum Ordering {
LESS = -1,
EQUAL = 0,
GREATER = 1,
}
/**
* This function switches the direction of `ordering` if `direction` is `"desc"`
* @param ordering The original ordering (assumed to be an "asc" ordering)
* @param direction The new desired direction
*/
export function rectifyOrdering(ordering: Ordering, direction: "asc" | "desc"): Ordering {
if (direction === "desc") {
return -ordering;
}
return ordering;
}
/**
* An ascending sorting function
* @param left An item from an array
* @param right An item from an array
* @returns The relative ordering in an ascending manner.
* - Less if left < right
* - Equal if left == right
* - Greater if left > right
*/
export function sortCompare<T>(left: T, right: T): Ordering {
if (left < right) {
return Ordering.LESS;
}
if (left === right) {
return Ordering.EQUAL;
}
return Ordering.GREATER;
}
/**
* This function sorts of list of items that have what should be a semver version formated string
* as the field `version` but if it is not loosely coercable to semver falls back to sorting them
* alphanumerically
*/
export function sortBySemverVersion<T extends { version: string }>(versioneds: T[]): T[] {
return versioneds
.map(versioned => ({
__version: coerce(versioned.version, { loose: true }),
raw: versioned,
}))
.sort((left, right) => {
if (left.__version && right.__version) {
return semver.compare(right.__version, left.__version);
}
if (!left.__version && right.__version) {
return Ordering.GREATER;
}
if (left.__version && !right.__version) {
return Ordering.LESS;
}
return sortCompare(left.raw.version, right.raw.version);
})
.map(({ raw }) => raw);
}