实用的js版本对比方法

225 阅读1分钟
/**
 * 对比版本大小
 *
 *  ## Usage
 *
 *  ```
 *  compareVersion(['1.3.0', '===', '1.2']) // false
 *  compareVersion(['1.3.0', '>=', '1.2'])  // true
 *  compareVersion(['1.3.0', '=>', '1.2'])  // true
 *  compareVersion(['1.3.0', '<=', '1.2'])  // false
 *  compareVersion(['1.3.0', '=<', '1.2'])  // false
 *  ```
 *
 * @param {*[]} args
 *
 * @return {boolean}
 */
export function compareVersion(args) {
  const operatorMap = {
    '>': 1,
    '=': 0,
    '<': -1
  };

  const v1 = args[0];
  const v2 = args[2];

  const operator = args[1];

  return _.uniq([...operator])
    .map((key) => operatorMap[key])
    .includes(getCompareVersionResult(v1, v2));
}

/**