Last active
August 29, 2015 14:17
-
-
Save jcayzac/7db80a737d6bfd21a5d2 to your computer and use it in GitHub Desktop.
Compare semantic versions
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
module.exports = function(a, b) { | |
const vA = /^(\d+)\.(\d+)(?:\.(\d+))?(.*)$/.exec(a), | |
vB = /^(\d+)\.(\d+)(?:\.(\d+))?(.*)$/.exec(b) | |
// Invalid version number go at the end | |
if (vA == null) return -1 | |
if (vB == null) return 1 | |
// Numeric version components | |
const nA = (vA[1] >>> 0) * 10000 + (vA[2] >>> 0) * 100 + (vA[3] >>> 0), | |
nB = (vB[1] >>> 0) * 10000 + (vB[2] >>> 0) * 100 + (vB[3] >>> 0) | |
if (nA < nB) return -1 | |
if (nA > nB) return 1 | |
// Same numeric version: compare stage names | |
const sA = vA[4], | |
sB = vB[4] | |
// Same stage name (or lack thereof) | |
if (sA === sB) return 0 | |
// No stage name for? Final versions come last | |
if (!sA) return 1 | |
if (!sB) return -1 | |
// Sort stage names lexicographically | |
return [sA, sB].sort()[0] === sA ? -1 : 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment