下面是另一个简短的版本,适用于任何数量的子版本,填充零和偶数字母(1.0.0b3)
const compareVer = ((prep, repl) =>
{
prep = t => ("" + t)
//treat non-numerical characters as lower version
//replacing them with a negative number based on charcode of first character
.replace(/[^0-9\.]+/g, c => "." + (c.replace(/[\W_]+/, "").toLowerCase().charCodeAt(0) - 65536) + ".")
//remove trailing "." and "0" if followed by non-numerical characters (1.0.0b);
.replace(/(?:\.0+)*(\.-[0-9]+)(\.[0-9]+)?\.*$/g, "$1$2")
.split('.');
return (a, b, c, i, r) =>
{
a = prep(a);
b = prep(b);
for (i = 0, r = 0, c = Math.max(a.length, b.length); !r && i++ < c;)
{
r = -1 * ((a[i] = ~~a[i]) < (b[i] = ~~b[i])) + (a[i] > b[i]);
}
return r;
}
})();
函数返回:
如果a = b则为0
1如果a > b
-1如果a < b
1.0 = 1.0.0.0.0.0
1.0 < 1.0.1
1.0b1 < 1.0
1.0b = 1.0b
1.1 > 1.0.1b
1.1alpha < 1.1beta
1.1rc1 > 1.1beta
1.1rc1 < 1.1rc2
1.1.0a1 < 1.1a2
1.1.0a10 > 1.1.0a1
1.1.0alpha = 1.1a
1.1.0alpha2 < 1.1b1
1.0001 > 1.00000.1.0.0.0.01
/*use strict*/
const compareVer = ((prep, repl) =>
{
prep = t => ("" + t)
//treat non-numerical characters as lower version
//replacing them with a negative number based on charcode of first character
.replace(/[^0-9\.]+/g, c => "." + (c.replace(/[\W_]+/, "").toLowerCase().charCodeAt(0) - 65536) + ".")
//remove trailing "." and "0" if followed by non-numerical characters (1.0.0b);
.replace(/(?:\.0+)*(\.-[0-9]+)(\.[0-9]+)?\.*$/g, "$1$2")
.split('.');
return (a, b, c, i, r) =>
{
a = prep(a);
b = prep(b);
for (i = 0, r = 0, c = Math.max(a.length, b.length); !r && i++ < c;)
{
r = -1 * ((a[i] = ~~a[i]) < (b[i] = ~~b[i])) + (a[i] > b[i]);
}
return r;
}
})();
//examples
let list = [
["1.0", "1.0.0.0.0.0"],
["1.0", "1.0.1"],
["1.0b1", "1.0"],
["1.0b", "1.0b"],
["1.1", "1.0.1b"],
["1.1alpha", "1.1beta"],
["1.1rc1", "1.1beta"],
["1.1rc1", "1.1rc2"],
["1.1.0a1", "1.1a2"],
["1.1.0a10", "1.1.0a1"],
["1.1.0alpha", "1.1a"],
["1.1.0alpha2", "1.1b1"],
["1.0001", "1.00000.1.0.0.0.01"]
]
for(let i = 0; i < list.length; i++)
{
console.log( list[i][0] + " " + "<=>"[compareVer(list[i][0], list[i][1]) + 1] + " " + list[i][1] );
}
https://jsfiddle.net/vanowm/p7uvtbor/