Created
May 11, 2012 21:06
-
-
Save dieseltravis/2662417 to your computer and use it in GitHub Desktop.
comparing version strings
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
// hacky numeric conversion: | |
//BUG: this will fail comparing "x.y" to "x.ypre" | |
var getVersion = function (versionString) { | |
var values = versionString.split("."), | |
version = 0, | |
factor = 0.0001; | |
for (var i = 0, l = values.length; i < l; i++) { | |
version += parseInt(values[i], 10) * Math.pow(factor, i); | |
} | |
return version; | |
}; | |
// Example usage: | |
if (getVersion(jQuery.fn.jquery) >= getVersion("1.3")) { | |
// don't use @ in attr selectors | |
} | |
// quick & dirty version: | |
//BUG: this will fail comparing "x.y" to "x.y.0" | |
//BUG: this will fail comparing "x.y" to "x.ypre" | |
var versionGTE = function (valueA, valueB) { | |
var values = [valueA, valueB]; | |
values.sort(); | |
// if valueA > valueB, values will have switched | |
return (values[1] === valueA); | |
}; | |
// compact version: | |
var versionGTE = function (valueA, valueB) { | |
return ([valueA, valueB].sort()[1] === valueA); | |
}; | |
// Example usage: | |
if (versionGTE(jQuery.fn.jquery, "1.3")) { | |
// don't use @ in attr selectors | |
} | |
// long & hairy version: | |
var versionCompare = function (versionStringA, versionStringB) { | |
// quick test of equality before digging in | |
if (versionStringA === versionStringB) return 0; | |
var versionedAlpha = /[a-z]+(\d+)/gi, | |
getArray = function (verString) { | |
// replace rc1, rc2, beta3, etc with .-1.1, .-1.2, .-1.3, etc | |
return verString.replace(versionedAlpha, ".-1.$1").split("."); | |
}, | |
valuesA = getArray(versionStringA), | |
valuesB = getArray(versionStringB), | |
maxLength = Math.max(valuesA.length, valuesB.length), | |
hasLetters = /[a-z]/gi, | |
// assume any version with letters is -1 (pre, rc, etc) | |
// also assume that any null entries are 0 (1.5 === 1.5.0) | |
parseVersion = function (verString) { | |
return (verString) ? (hasLetters.test(verString)) ? -1 : parseInt(verString, 10) : 0; | |
}; | |
// verify both arrays are the same size | |
valuesA.length = maxLength; | |
valuesB.length = maxLength; | |
for (var i = 0; i < maxLength; i++) { | |
var valueA = parseVersion(valuesA[i]), | |
valueB = parseVersion(valuesB[i]); | |
if (valueA < valueB) { | |
return -1; | |
} else if (valueA > valueB) { | |
return 1; | |
} | |
} | |
// all equal at this point | |
return 0; | |
}; | |
// Example usage: | |
if (versionCompare(jQuery.fn.jquery, "1.3") >= 0) { | |
// don't use @ in attr selectors | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/2664255