Skip to content

Instantly share code, notes, and snippets.

@jakerella
Created September 30, 2014 19:50
Show Gist options
  • Save jakerella/05fd72b9dcbed2ed930f to your computer and use it in GitHub Desktop.
Save jakerella/05fd72b9dcbed2ed930f to your computer and use it in GitHub Desktop.
Semver Comparison
function test() {
var results = [];
results.push(compareSemver("1.8.3", "1.8.3", "=="));
results.push(compareSemver("1.9.1", "1.11.1", "<"));
results.push(compareSemver("1.5.3", "1.9", "<"));
results.push(compareSemver("1.3.2", "1.10.2", "<="));
results.push(compareSemver("1.3.2", "1.3.2", "<="));
results.push(compareSemver("1.11.1", "1.9.1", ">"));
results.push(compareSemver("1.11.1", "1.11.0", ">"));
results.push(compareSemver("1.10.2", "1.5.2", ">="));
console.log(results);
}
function compareSemver(v1, v2, op) {
var result = false,
p1 = normalizeSemVer(v1),
p2 = normalizeSemVer(v2);
if (/^===?$/.test(op)) {
result = semverEqual(p1, p2, 3);
} else if (/^</.test(op)) {
result = p1[0] < p2[0] || (semverEqual(p1, p2, 1) && p1[1] < p2[1]) || (semverEqual(p1, p2, 2) && p1[2] < p2[2]);
if (!result && /^<=$/.test(op)) {
result = semverEqual(p1, p2, 3);
}
} else if (/^>/.test(op)) {
result = p1[0] > p2[0] || (semverEqual(p1, p2, 1) && p1[1] > p2[1]) || (semverEqual(p1, p2, 2) && p1[2] > p2[2]);
}
if (!result && /^[<>]=$/.test(op)) {
result = semverEqual(p1, p2, 3);
}
return result;
}
function semverEqual(p1, p2, cnt) {
var i, equal = true;
for (i=0; i<cnt; ++i) {
equal = equal && (p1[i] === p2[i]);
}
return equal;
}
function normalizeSemVer(v) {
if (v.length < 1) { return "0.0.0"; }
var p = v.toString().split('.');
if (p.length < 2) { p[1] = "0"; }
if (p.length < 3) { p[2] = "0"; }
return [Number(p[0]), Number(p[1]), Number(p[2])];
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment