Created
October 12, 2015 09:00
-
-
Save samuelsmal/57f58c2f9de5bf531887 to your computer and use it in GitHub Desktop.
Javascript API Version comparator function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Compares two given API version strings in base 10. Only numbers separated by a dot (".") are supported. | |
* It compares lhs < rhs and returns the default UNIX comparison identifier: | |
* | |
* if lhs < rhs | |
* return -1 | |
* else if lhs > rhs | |
* return 1 | |
* else | |
* return 0 | |
*/ | |
function compareApiVersions (lhs, rhs) { | |
var lhs_tokens = lhs.split('.') | |
var rhs_tokens = rhs.split('.') | |
lhs_tokens.forEach(function (el) { | |
el = parseInt(el, 10) | |
}) | |
rhs_tokens.forEach(function (el) { | |
el = parseInt(el, 10) | |
}) | |
for (var i = 0, max = Math.max(lhs_tokens.length, rhs_tokens.length); i < max; i++) { | |
// pfm: 0.1 && el: 0.2 => true | |
// pfm: 0.1 && el: 0.1.1 => true | |
var l = lhs_tokens[i] || 0 | |
var r = rhs_tokens[i] || 0 | |
if (l < r) { | |
return -1 | |
} | |
if (l > r) { | |
return 1 | |
} | |
} | |
return 0 | |
} | |
// Tests | |
console.log(compareApiVersions("1.1.1", "1.1.1") === 0) | |
console.log(compareApiVersions("1.1.1", "1.1.1.1") === -1) | |
console.log(compareApiVersions("1.1.1", "1.1.0.1") === 1) | |
console.log(compareApiVersions("1.2.1", "1.1.1.1") === 1) | |
console.log(compareApiVersions("1.2.1", "1.12.1.1") === 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment