Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare two version numbers that follows the semantic version standard
/**
* 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
You can’t perform that action at this time.