Version compare util from ChatGPT

This commit is contained in:
shamoon committed 2026-11-17 23:14:30 -08:00
1 parent c091766a86
commit 9f57da5193
2 files changed
+24

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
import { compareVersions } from './version'
describe('compareVersions', () => {
it('should compare versions numerically', () => {
expect(compareVersions('3.5.1', '3.5.0')).toBeGreaterThan(0)
expect(compareVersions('3.10.0', '3.9.9')).toBeGreaterThan(0)
expect(compareVersions('3.4.2', '3.5.0')).toBeLessThan(0)
expect(compareVersions('3.5.0', '3.5.0')).toEqual(0)
expect(compareVersions('3.5', '3.5.0')).toEqual(0)
})
})
+13
View File
@@ -0,0 +1,13 @@
/**
* Compare two X.Y.Z version strings numerically.
* Returns a positive number if a > b, negative if a < b, 0 if equal.
*/
export function compareVersions(a: string, b: string): number {
const partsA = a.split('.').map((p) => parseInt(p, 10) || 0)
const partsB = b.split('.').map((p) => parseInt(p, 10) || 0)
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0)
if (diff !== 0) return diff
}
return 0
}