Semantic versioning gives every release a string like 1.4.2 or 2.0.0-rc.1 together with a precise rule for which release comes first. You are implementing that rule: semverCompare(a, b) parses two version strings and returns -1, 0, or 1 depending on which has the lower precedence. The format is MAJOR.MINOR.PATCH with an optional prerelease tag after a hyphen and optional build metadata after a plus sign. See the Semantic Versioning spec for the full precedence rules.
semverCompare(a: string, b: string): -1 | 0 | 1
// -1 a has lower precedence than b (a comes first)
// 0 a and b have equal precedence
// 1 a has higher precedence than b
semverCompare('1.2.3', '1.2.3'); // 0
semverCompare('1.0.10', '1.0.9'); // 1 (10 beats 9 numerically)
semverCompare('1.0.0-alpha', '1.0.0'); // -1 (a prerelease precedes the release)
semverCompare('1.0.0-beta.2', '1.0.0-beta.11'); // -1 (2 is below 11 as numbers)
semverCompare('1.0.0-alpha.1', '1.0.0-alpha.beta'); // -1 (a number ranks below a word)
semverCompare('1.0.0+build.9', '1.0.0'); // 0 (build metadata is ignored)
major, then minor, then patch as numbers, left to right; the first that differs decides the result.1.0.0-alpha precedes 1.0.0.+ has no effect on ordering.-1, 0, or 1 — not a raw difference of two numbers.Unlock the solution & editor
Runnable editor + tests
Solve in the browser with instant Jest feedback.
Detailed solutions
Walkthroughs, edge cases, and complexity notes.
Multi-framework variants
React, Vue, Vanilla, Angular — same question, different stacks.