Skip to content

Instantly share code, notes, and snippets.

@int64ago
Forked from alexey-bass/compare.js
Created December 29, 2015 06:08
Show Gist options
  • Save int64ago/2732b0f5df4faf282fd2 to your computer and use it in GitHub Desktop.
Save int64ago/2732b0f5df4faf282fd2 to your computer and use it in GitHub Desktop.
JavaScript version compare
/**
* Simply compares two string version values.
*
* Example:
* versionCompare('1.1', '1.2') => -1
* versionCompare('1.1', '1.1') => 0
* versionCompare('1.2', '1.1') => 1
* versionCompare('2.23.3', '2.22.3') => 1
*
* Returns:
* -1 = left is LOWER than right
* 0 = they are equal
* 1 = left is GREATER = right is LOWER
* And FALSE if one of input versions are not valid
*
* @function
* @param {String} left Version #1
* @param {String} right Version #2
* @return {Integer|Boolean}
* @author Alexey Bass (albass)
* @since 2011-07-14
*/
versionCompare = function(left, right) {
if (typeof left + typeof right != 'stringstring')
return false;
var a = left.split('.')
, b = right.split('.')
, i = 0, len = Math.max(a.length, b.length);
for (; i < len; i++) {
if ((a[i] && !b[i] && parseInt(a[i]) > 0) || (parseInt(a[i]) > parseInt(b[i]))) {
return 1;
} else if ((b[i] && !a[i] && parseInt(b[i]) > 0) || (parseInt(a[i]) < parseInt(b[i]))) {
return -1;
}
}
return 0;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>QUnit Test Suite</title>
<link rel="stylesheet" href="qunit/qunit.css">
<script src="qunit/qunit.js"></script>
<script src="compare.js"></script>
<script src="tests.qunit.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture">test markup</div>
</body>
</html>
test('invalid input', function() {
equal(versionCompare(1, '2'), false);
equal(versionCompare('2', 1), false);
equal(versionCompare(3, 3), false);
equal(versionCompare(true, false), false);
equal(versionCompare(window, document), false);
});
test('one digit', function() {
equal(versionCompare('1', '2'), -1);
equal(versionCompare('2', '1'), 1);
equal(versionCompare('3', '3'), 0);
});
test('many sections', function() {
equal(versionCompare('2.22', '2.22'), 0);
equal(versionCompare('2.23', '2.22'), 1);
equal(versionCompare('2.22', '2.23'), -1);
equal(versionCompare('2.22.0', '2.22.0'), 0);
equal(versionCompare('2.22.1', '2.22.0'), 1);
equal(versionCompare('2.22.1', '2.23.1'), -1);
});
test('not equal sections', function() {
equal(versionCompare('2', '2.0'), 0);
equal(versionCompare('2', '2.1'), -1);
equal(versionCompare('2.1', '2'), 1);
});
test('LarryKim comment 120330', function() {
equal(versionCompare('5', '3000'), -1);
equal(versionCompare('3000', '5'), 1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment