Skip to content

Instantly share code, notes, and snippets.

@ripter
Created January 30, 2015 18:44
Show Gist options
  • Select an option

  • Save ripter/bf5c903e50ee0ffbd55d to your computer and use it in GitHub Desktop.

Select an option

Save ripter/bf5c903e50ee0ffbd55d to your computer and use it in GitHub Desktop.
makeshift semantic version comparison
// makeshift semantic version comparisons
// standard compareFunction
// Checks if semver a is greater than semver b
function gtSemver(a, b) {
// validate
if (!a && !b) { return 0; }
if (!a) { return -1; }
if (!b) { return 1; }
if (!_.isString(a) || !_.isString(b)) {
throw new Error('Semver not valid "' + a + '", "' + b + '"');
}
// helpers
var reg = /(\d+)\.(\d+)\.(\d+)(-?.*)/;
var toInt = function(num) { return parseInt(num, 10); };
var cmp = function(a, b) {
if (a < b) { return -1; }
if (a > b) { return 1; }
return 0;
};
// break the semver into parts
a = a.match(reg);
b = b.match(reg);
// we can only compare numbers (per semver)
a = a.slice(1, 4);
b = b.slice(1, 4);
// to numbers!
a = a.map(toInt);
b = b.map(toInt);
// compare in order
return cmp(a[0], b[0]) || cmp(a[1], b[1]) || cmp(a[2], b[2]);
}
@ripter

ripter commented Jan 30, 2015

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment