Last active
August 29, 2015 14:04
-
-
Save ryangibson/a398e1eb1941a3ccfb04 to your computer and use it in GitHub Desktop.
Simple version parse and compare.
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
function Version(versionString) { | |
this.version = { | |
major: 0, | |
minor: 0, | |
patch: 0 | |
}; | |
if (versionString) { | |
this.parse(versionString); | |
} | |
} | |
Version.prototype.parse = function (versionString) { | |
var chunks = versionString.split('.'); | |
var getIntValue = function (value) { | |
var i = parseInt(value, 10); | |
return isNaN(i) ? 0 : i; | |
} | |
switch (chunks.length) { | |
case 3: | |
this.version.patch = getIntValue(chunks[2]); | |
case 2: | |
this.version.minor = getIntValue(chunks[1]); | |
case 1: | |
this.version.major = getIntValue(chunks[0]); | |
break; | |
default: | |
this.version.major = getIntValue(versionString); | |
} | |
} | |
Version.prototype.toArray = function (truncate) { | |
var output = [this.version.major, this.version.minor, this.version.patch]; | |
if (truncate) { | |
var newLength = output.length; | |
for (var i = output.length - 1; i > 0; --i) { | |
if (output[i] <= 0) { | |
newLength--; | |
} else { | |
break; | |
} | |
} | |
return output.slice(0, newLength); | |
} | |
return output; | |
} | |
Version.prototype.toString = function (truncate) { | |
return this.toArray(truncate).join('.') | |
} | |
/* | |
* Return 1 if the receiver is greater than the argument. | |
* Return 0 if the receiver and the argument are equal. | |
* Return -1 if the receiver is less than the argument. | |
**/ | |
Version.prototype.compare = function (toVersion) { | |
var fma = this.version.major; | |
var fmi = this.version.minor; | |
var fpa = this.version.patch; | |
var tma = toVersion.version.major; | |
var tmi = toVersion.version.minor; | |
var tpa = toVersion.version.patch; | |
if (fma == tma && fmi == tmi && fpa == tpa) { | |
return 0; | |
} else if (fma > tma || | |
(fma == tma && fmi > tmi) || | |
(fma == tma && fmi == tmi && fpa > tpa) | |
) { | |
return 1; | |
} | |
return -1; | |
} | |
Version.prototype.compareToVersionString = function (toVersionString) { | |
return this.compare(new Version(toVersionString)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment