Skip to content

Instantly share code, notes, and snippets.

@ryangibson
Created December 3, 2015 12:04
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 ryangibson/caed90042db51a3be88f to your computer and use it in GitHub Desktop.
Save ryangibson/caed90042db51a3be88f to your computer and use it in GitHub Desktop.
Simple sem ver class.
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));
}
module.exports = Version;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment