Skip to content

Instantly share code, notes, and snippets.

@davidraviv
Created February 3, 2016 09:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidraviv/20074208d6eeaa98f843 to your computer and use it in GitHub Desktop.
Save davidraviv/20074208d6eeaa98f843 to your computer and use it in GitHub Desktop.
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