function* walk(str) {
let part = '';
let terminals = ['.', '-'];
for (let i = 0; i < str.length; i++) {
if (terminals.includes(str[i])) {
yield part;
part = '';
} else {
part += str[i];
}
}
if (part) {
yield part;
}
}
function compareVersions(v1, v2) {
const iterator1 = walk(v1);
const iterator2 = walk(v2);
while (true) {
const part1 = iterator1.next().value;
const part2 = iterator2.next().value;
if (part1 === undefined && part2 === undefined) {
return 0; // Both versions are equal
}
if (part1 === undefined) return -1; // v1 is smaller
if (part2 === undefined) return 1; // v2 is smaller
const num1 = parseInt(part1, 10);
const num2 = parseInt(part2, 10);
if (num1 > num2) return 1;
if (num1 < num2) return -1;
}
}
let versions = ['12.1.3', '12.44.11', '11.43.11'];
let highestVersion = versions[0];
for (let i = 1; i < versions.length; i++) {
if (compareVersions(versions[i], highestVersion) > 0) {
highestVersion = versions[i];
}
}
console.log('Highest version:', highestVersion);
js比较多个版本号并输出
最新推荐文章于 2024-08-22 14:32:34 发布