Created
February 3, 2016 09:03
-
-
Save davidraviv/20074208d6eeaa98f843 to your computer and use it in GitHub Desktop.
Compare two version numbers that follows the semantic version standard
This file contains 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
/** | |
* Created by david on 17/1/16. | |
*/ | |
/** | |
* Compares two version numbers that follow the semantic version standard. | |
* Compares only the first 3 elements (major, minor and patch). | |
* Separator can be '.' or '-'. | |
* If a>b, returns 1 | |
* If a<b, returns -1 | |
* If a=b, returns 0 | |
* @param a | |
* @param b | |
* @returns {number} | |
*/ | |
module.exports = function compare(a, b) { | |
var pa = a.split(/[\.\-]/); // split by either '.' or '-' | |
var pb = b.split(/[\.\-]/); | |
for (var i = 0; i < 3; i++) { | |
var na = Number(pa[i]); | |
var nb = Number(pb[i]); | |
if (na > nb) return 1; | |
if (nb > na) return -1; | |
if (!isNaN(na) && isNaN(nb)) return 1; | |
if (isNaN(na) && !isNaN(nb)) return -1; | |
} | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment