Skip to content

Commit 6aabe39

Browse files
committed
fix: version sorter Not working well
1 parent 500352a commit 6aabe39

1 file changed

Lines changed: 18 additions & 15 deletions

File tree

src/helpers/versionSorter.ts

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,27 @@
44
* @author TheRolf
55
*/
66
export default function versionSorter(a: string, b: string) {
7-
const aSplit = a.split(".").map((s) => parseInt(s, 10));
8-
const bSplit = b.split(".").map((s) => parseInt(s, 10));
7+
const aStrings = a.split(".");
8+
const aNumbers = aStrings.map((part) => Number(part));
9+
const bStrings = b.split(".");
10+
const bNumbers = bStrings.map((part) => Number(part));
911

10-
if (aSplit.includes(NaN) || bSplit.includes(NaN)) {
11-
return String(a).localeCompare(String(b)); // compare as strings
12+
// non-numbered versions go above everything else
13+
if (aNumbers.every((a) => isNaN(a)) || bNumbers.every((b) => isNaN(b))) {
14+
return a.localeCompare(b);
1215
}
1316

14-
const upper = Math.min(aSplit.length, bSplit.length);
15-
let result = 0;
16-
for (let i = 0; i < upper && result === 0; ++i) {
17-
// each number in version
18-
if (aSplit[i] === bSplit[i]) result = 0;
19-
else result = aSplit[i] < bSplit[i] ? -1 : 1;
20-
}
17+
// compare only the safely accessible parts (1.17 vs 1.18.2 ignores the .2)
18+
const upper = Math.min(aNumbers.length, bNumbers.length);
2119

22-
if (result !== 0) return result;
20+
// compare each part by priority and immediately return if we find a difference
21+
for (let i = 0; i < upper; ++i) {
22+
const result = aNumbers[i] - bNumbers[i];
23+
// any version with a letter in it (e.g. b1.7.3) goes below everything else
24+
if (isNaN(result)) return bStrings[i].localeCompare(aStrings[i]);
25+
if (result !== 0) return result;
26+
}
2327

24-
if (aSplit.length === bSplit.length) return 0;
25-
// longer length wins
26-
return aSplit.length < bSplit.length ? -1 : 1;
28+
// each part in the safe boundary is the same, try for differing length (1.17 vs 1.17.1)
29+
return aNumbers.length - bNumbers.length;
2730
}

0 commit comments

Comments
 (0)