版本号规范

参考https://semver.org/lang/zh-CN/

1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1

具体实现

function compareVersion(v1, v2) {
  function* getStepVersion(v) {
    const matchReg = /(\.|\-)/; // 匹配到任意一项,则返回分段的版本号
    // 将先行版本号,转换成数字,直接比大小
    const specialVersionTransObj = {
      alpha: -3,
      beta: -2,
      rc: -1,
    };
    let tmp = ""; // 存储每段版本的值
    for (let i = 0; i <= v.length - 1; i++) {
      let item = v[i];
      if (matchReg.test(item)) {
        yield specialVersionTransObj[tmp] || tmp;
        tmp = "";
      } else {
        tmp += item;
      }
    }

    // 遍历至最后一项,没有匹配到.-也要返回结果
    if (tmp) {
      yield specialVersionTransObj[tmp] || tmp;
    }
  }

  const v1Iterator = getStepVersion(v1);
  const v2Iterator = getStepVersion(v2);

  let isEnd = false;
  let isHighLevel = false;
    // 每次遍历相当于,2个版本号分段间的比较
  while (!isEnd) {
    const item1 = v1Iterator.next();
    const item2 = v2Iterator.next();
    item1.value = item1.value || 0;
    item2.value = item2.value || 0;
    
    if (item1.done && item2.done) {
        // 代表版本号一致
      isEnd = true;
    } else {
      if (Number(item2.value) > Number(item1.value)) {
        // v2 版本大于 v1
        isHighLevel = true;
        isEnd = true;
      } else if (Number(item2.value) < Number(item1.value)) {
        // v2 版本小于 v1
        isHighLevel = false;
        isEnd = true;
      }
    }
  }
  return isHighLevel;
}

单元测试

compareVersion("2.3.4", "1.3.4"); // false
compareVersion("2.3.4", "1.4.4"); // false
compareVersion("2.3.4", "2.3.4.alpha"); // false
compareVersion("2.3.4.alpha-1", "2.3.4.alpha-2"); // true
compareVersion("2.3.4.alpha-2", "2.3.4.beta"); // true
compareVersion("2.3.4.alpha", "1..4.alpha"); // false
compareVersion("2.3.4.alpha", "2.3.4.alpha"); // false
compareVersion("2.3.4.alpha", "3.3.4.alpha"); // true
compareVersion("2.3.4.alpha", "2.2.4.alpha"); // false
compareVersion("2.3.4.alpha", "2.4.4.alpha"); // true
compareVersion("2.3.4.alpha", "2.4.4.alpha"); // true

icezero
28 声望3 粉丝