Skip to content

Instantly share code, notes, and snippets.

@boltex
Created July 23, 2015 19:49
Show Gist options
  • Save boltex/9ff1c16a0e6f1e314314 to your computer and use it in GitHub Desktop.
Save boltex/9ff1c16a0e6f1e314314 to your computer and use it in GitHub Desktop.
cmpVersion Is a javascript utility function to compare version strings with multiple decimal points. (such as "1.1.13")
function cmpVersion(a, b) {
var i, cmp, len, re = /(\.0)+[^\.]*$/;
a = (a + '').replace(re, '').split('.');
b = (b + '').replace(re, '').split('.');
len = Math.min(a.length, b.length);
for( i = 0; i < len; i++ ) {
cmp = parseInt(a[i], 10) - parseInt(b[i], 10);
if( cmp !== 0 ) {
return cmp;
}
}
return a.length - b.length;
}
function assert(x) {
if (!x) {
alert("Assert failed");
debugger;
}
}
assert(cmpVersion("1.7.1", "1.7.10") < 0);
assert(cmpVersion("1.7.2", "1.7.10") < 0);
assert(cmpVersion("1.6.1", "1.7.10") < 0);
assert(cmpVersion("1.6.20", "1.7.10") < 0);
assert(cmpVersion("1.7.1", "1.7.10") < 0);
assert(cmpVersion("1.7", "1.7.0") == 0);
assert(cmpVersion("1.7", "1.8.0") < 0);
assert(cmpVersion("1.7.10", "1.7.1") > 0);
assert(cmpVersion("1.7.10", "1.6.1") > 0);
assert(cmpVersion("1.7.10", "1.6.20") > 0);
assert(cmpVersion("1.7.0", "1.7") == 0);
assert(cmpVersion("1.8.0", "1.7") > 0);
assert(cmpVersion("1.7.10", "1.7.10") === 0);
assert(cmpVersion("1.7", "1.7") === 0);
assert(cmpVersion("1.7", "1.7.0") === 0);
assert(isNaN(cmpVersion("1.7", "1..7")));
assert(isNaN(cmpVersion("1.7", "Bad")));
assert(isNaN(cmpVersion("1..7", "1.7")));
assert(isNaN(cmpVersion("Bad", "1.7")));
alert("All done");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment