Problems › TypeScript › validation
Compare two version strings
A deploy tool decides whether the version on the server is behind the one being released.
- Versions are dot-separated numbers: 1.2.10 has parts 1, 2 and 10.
- Compare part by part numerically, so 1.10 is above 1.2 — not below it, as a text sort would have it.
- A missing part counts as zero, so 1.2 and 1.2.0 are the same version.
- Leading zeros mean nothing: 1.01 is 1.1.
- Return -1 when the first is older, 1 when it is newer, 0 when they match.
compareVersions(first: string, second: string) → int
Where you start
function compareVersions(first: string, second: string): number {
}
Worked examples
| Call | Result |
|---|---|
compareVersions("1.2.10", "1.10.2") | -1 |
compareVersions("1.2", "1.2.0") | 0 |
compareVersions("2.0", "1.9.9") | 1 |
compareVersions("1.0.0", "1.0.0") | 0 |
Hint
Walk both to the length of the longer one, reading a missing part as zero.
Reference solution in TypeScript
function compareVersions(first: string, second: string): number {
const a = first.split('.');
const b = second.split('.');
const n = Math.max(a.length, b.length);
for (let i = 0; i < n; i++) {
const x = i < a.length ? parseInt(a[i], 10) : 0;
const y = i < b.length ? parseInt(b[i], 10) : 0;
if (x !== y) return x < y ? -1 : 1;
}
return 0;
}