Skip to content

Instantly share code, notes, and snippets.

@ShenJack
Last active June 15, 2020 11:57
Show Gist options
  • Save ShenJack/8a86a76b679c9b6eef0607ae9b61e7a3 to your computer and use it in GitHub Desktop.
Save ShenJack/8a86a76b679c9b6eef0607ae9b61e7a3 to your computer and use it in GitHub Desktop.
VersionCompare
function versionCompare(version1, version2) {
//提取各个版本号并check
let [a1, b1, c1, plus1] = matchVersionNumber(version1)
let [a2, b2, c2, plus2] = matchVersionNumber(version2)
//乘以数字自动将字符串转型成数字
let result1 = a1 * 10000 * 10000 + b1 * 10000 + c1 * 1;
let result2 = a2 * 10000 * 10000 + b2 * 10000 + c2 * 1;
if (result1 !== result2) {
if (result1 > result2) {
return 1;
} else {
return -1;
}
}
//然后比较 小版本
if (plus1 > plus2) {
return 1;
} else if (plus1 === plus2) {
return 0;
} else {
return -1;
}
}
function matchVersionNumber(versionNumber) {
let reg = /([0-9]{1,4})\.([0-9]{1,4})\.([0-9]{1,4})-?(beta|alpha)?/;
let matchResult1 = versionNumber.match(reg)
if (matchResult1 == null) {
throw versionNumber + ' is not a valid version number'
}
let [match1, a, b, c, plus] = matchResult1;
return [a, b, c, plus]
}
console.log(versionCompare('1.0.2-alpha', '1.0.1-beta'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment