// 轻量级语义版本比较 export
export function compare(v1, v2, complete) {
v1 = String(v1)
v2 = String(v2)
if (v1 === v2) return 0
const v1s = v1.split('.')
const v2s = v2.split('.')
const len = Math[complete ? 'max' : 'min'](v1s.length, v2s.length)
for (let i = 0; i < len; i++) {
v1s[i] = 'undefined' === typeof v1s[i] ? 0 : parseInt(v1s[i], 10)
v2s[i] = 'undefined' === typeof v2s[i] ? 0 : parseInt(v2s[i], 10)
if (v1s[i] > v2s[i]) {
return 1
}
if (v1s[i] < v2s[i]) {
return -1
}
}
return 0
}
/**
* 版本判断
* new Version("6.1").eq(6); // true.
* new Version("6.1.2").eq("6.1"); // true.
*
* @export
* @class Version
*/
export class Version {
constructor(version, comparatorFunction) {
this._version = String(version)
this.delimiter = '.'
if (comparatorFunction) {
this.compare = comparatorFunction
}
}
compare(v1, v2, bool = true) {
return compare(v1, v2, bool)
}
// .eq("6.1", "6"); // true.
// .eq("6.1.2", "6.1"); // true.
eq(v1, v2 = this._version) {
return this.compare(v2, v1, false) === 0
}
gt(v1, v2 = this._version) {
return this.compare(v2, v1, true) > 0
}
gte(v1, v2 = this._version) {
return this.compare(v2, v1, true) >= 0
}
lt(v1, v2 = this._version) {
return this.compare(v2, v1, true) < 0
}
lte(v1, v2 = this._version) {
return this.compare(v2, v1, true) <= 0
}
valueOf() {
const { delimiter } = this
return parseFloat(
this._version
.split(delimiter)
.slice(0, 2)
.join(delimiter),
10
)
}
toString(precision) {
const { delimiter } = this
return 'undefined' === typeof precision
? this._version
: this._version
.split(delimiter)
.slice(0, precision)
.join(delimiter)
}
}