Created
January 30, 2015 18:44
-
-
Save ripter/bf5c903e50ee0ffbd55d to your computer and use it in GitHub Desktop.
makeshift semantic version comparison
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
| // makeshift semantic version comparisons | |
| // standard compareFunction | |
| // Checks if semver a is greater than semver b | |
| function gtSemver(a, b) { | |
| // validate | |
| if (!a && !b) { return 0; } | |
| if (!a) { return -1; } | |
| if (!b) { return 1; } | |
| if (!_.isString(a) || !_.isString(b)) { | |
| throw new Error('Semver not valid "' + a + '", "' + b + '"'); | |
| } | |
| // helpers | |
| var reg = /(\d+)\.(\d+)\.(\d+)(-?.*)/; | |
| var toInt = function(num) { return parseInt(num, 10); }; | |
| var cmp = function(a, b) { | |
| if (a < b) { return -1; } | |
| if (a > b) { return 1; } | |
| return 0; | |
| }; | |
| // break the semver into parts | |
| a = a.match(reg); | |
| b = b.match(reg); | |
| // we can only compare numbers (per semver) | |
| a = a.slice(1, 4); | |
| b = b.slice(1, 4); | |
| // to numbers! | |
| a = a.map(toInt); | |
| b = b.map(toInt); | |
| // compare in order | |
| return cmp(a[0], b[0]) || cmp(a[1], b[1]) || cmp(a[2], b[2]); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Codepen: http://codepen.io/anon/pen/XJaGeP?editors=101