xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

如何使用 js 实现一个比较APP版本号的大小的版本号排序函数 All In One

如何使用 js 实现一个比较APP版本号的大小的版本号排序函数 All In One

js / ts

const months = ['March', 'Jan', 'Feb', 'Dec'];
let arr = months.sort();
console.log(arr);
// Array ["Dec", "Feb", "Jan", "March"]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

bug

/**
 * @param {string} version1
 * @param {string} version2
 * @return {number}
 */
var compareVersion = function(version1, version2) {
  if(version1 > version2) {
    return 1;
  }
  if(version1 < version2) {
    return -1;
  }
  return 0;
};

image

image

Q: 如何对一组包含多个字符串版本号的数组进行排序,字符串版本号有不定数量的 . 符号进行分割?

存在一组版本号数组,如 ['0.1.1', '2.3.3', '0.3002.1', '4.2', '4.3.5', '4.3.4.5'],怎么对这个版本号进行降序排序,实现排序后的结果为['4.3.5', '4.3.4.5', '2.3.3', '0.3002.1', '0.1.1']

A:

版本号比较大小
数组遍历

二维数组

sort a,b 元素 字符串 split . 展开成数组,
数组 push 0 对齐长度,动态对齐
字符串padding 0
parseint
返回 升序/逆序

  1. 原理分析:
  2. 代码实现

function autoRankVersions(arr, type="desc") {
 // 字符串相减 ❌  NaN bug
 // 字符串比较 ✅ ??? js engine 自动实现了
  return arr.sort((a, b) => a > b ? -1 : 1);
}

const arr = ['0.1.1',  '2.3.3', '0.3002.1',  '4.2',  '4.3.5',  '4.3.4.5'];

autoRankVersions(arr);
//  ['4.3.5', '4.3.4.5', '4.2', '2.3.3', '0.3002.1', '0.1.1']
autoRankVersions(arr, "desc");
//  ['4.3.5', '4.3.4.5', '4.2', '2.3.3', '0.3002.1', '0.1.1']

/*

['0.1.1',  '2.3.3', '0.3002.1',  '4.2',  '4.3.5',  '4.3.4.5'].sort((a, b) => a > b ? 1 : -1);
(6) ['0.1.1', '0.3002.1', '2.3.3', '4.2', '4.3.4.5', '4.3.5']
['0.1.1', '0.001.1',  '2.3.3', '0.3002.1',  '4.2',  '4.3.5',  '4.3.4.5'].sort((a, b) => a > b ? 1 : -1);
(7) ['0.001.1', '0.1.1', '0.3002.1', '2.3.3', '4.2', '4.3.4.5', '4.3.5']
['0.1.1', '0.001.1',  '2.3.3', '0.3002.1',  '4.2',  '4.3.5.006',  '4.3.4.5'].sort((a, b) => a > b ? 1 : -1);
(7) ['0.001.1', '0.1.1', '0.3002.1', '2.3.3', '4.2', '4.3.4.5', '4.3.5.006']

*/

image

// bug ❌
// 代码优化,复用逻辑
function removePrevZeros(str) {
  if(str.length > 1) {
    return str.replace(/^0+/, '');
  } else {
    return str;
  }
}

function autoAlignArray(a1, a2) {
  if(a1.length < a2.length) {
    let l = a2.length - a1.length;
    for (let i = 0; i < l; i++) {
      a1.push(`0`);
    }
  }
  if(a1.length > a2.length) {
    let l = a1.length - a2.length;
    for (let i = 0; i < l; i++) {
      a2.push(`0`);
    }
  }
  return [a1.map(i => removePrevZeros(i)), a2.map(i => removePrevZeros(i))]
}

function autoRankVersions(arr, type="desc") {
  // backup 原始数组
  arr.sort((a, b) => a > b ? -1 : 1);
  // return arr.sort((a, b) => {
  //   const a1 = a.split(`.`);
  //   const a2 = b.split(`.`);
  //   console.log(`a, b =`, a, b);
  //   const [arr1, arr2] = autoAlignArray(a1, a2);
  //   console.log(`arr1, arr2 =`, arr1, arr2);
  //   for (let i = 0; i < arr1.length; i++) {
  //     if(parseInt(arr1[i]) > parseInt(arr2[i])) {
  //       return 1;
  //     } else {
  //       return -1;
  //     }
  //   }
  // });
}

const arr = ['0.1.1',  '2.3.3', '0.3002.1',  '4.2',  '4.3.5',  '4.3.4.5'];

autoRankVersions(arr);

'1.01' > '1.001' bug ???

`0.1.1` > `0.001.1`
// true

image


function removePrevZeros(str) {
  if(str.length > 1) {
    return str.replace(/^0+/, '');
  } else {
    return str;
  }
}

function autoAlignArray(a1, a2) {
  if(a1.length < a2.length) {
    let l = a2.length - a1.length;
    for (let i = 0; i < l; i++) {
      a1.push(`0`);
    }
  }
  if(a1.length > a2.length) {
    let l = a1.length - a2.length;
    for (let i = 0; i < l; i++) {
      a2.push(`0`);
    }
  }
  return [a1.map(i => removePrevZeros(i)), a2.map(i => removePrevZeros(i))]
}

function autoRankVersions(arr, type="desc") {
  // backup 原始数组
  return arr.sort((a, b) => a > b ? -1 : 1);
}

const arr = ['1.001','1.01','0.1.1',  '2.3.3', '0.3002.1',  '4.2',  '4.3.5',  '4.3.4.5'];

autoRankVersions(arr);
// ['4.3.5', '4.3.4.5', '4.2', '2.3.3', '1.01', '1.001', '0.3002.1', '0.1.1']

image

TypeScript

// 枚举类型
// enum Types {
//   "desc",
//   "asc"
// };

enum Types {
  "desc" = "desc",
  "asc" = "asc",
};

function autoRankVersions(arr: string[], type: Types = Types.desc) {
  //
}
// 联合类型
type RankType = "desc" | "asc";

function autoRankVersions(arr: string[], type: RankType = "desc") {
  //
}


https://www.typescriptlang.org/play/

leetcode

  1. Compare Version Numbers

  2. 比较版本号

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2023-03-03
 * @modified
 *
 * @description 165. Compare Version Numbers
 * @description 165. 比较版本号
 * @difficulty Medium
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/compare-version-numbers/
 * @link https://leetcode.cn/problems/compare-version-numbers/
 *
 * @solutions https://leetcode.com/problems/compare-version-numbers/submissions/908456812/
 *
 * @best_solutions
 *
 */

// export {};

const log = console.log;

function compareVersion(version1: string, version2: string): number {
  let a1 = version1.split(`.`);
  let a2 = version2.split(`.`);
  // 代码优化,复用逻辑
  function removePrevZeros(str) {
    if(str.length > 1) {
      return str.replace(/^0+/, '');
    } else {
      return str;
    }
  }
  function autoAlignArray(a1, a2) {
    if(a1.length === a2.length) {
      return [a1.map(i => removePrevZeros(i)), a2.map(i => removePrevZeros(i))];
    }
    let arr1:string[] = [];
    let arr2:string[] = [];
    if(a1.length < a2.length) {
      arr1 = [...a1];
      arr2 = [...a2];
    }
    if(a1.length > a2.length) {
      arr1 = [...a2];
      arr2 = [...a1];
    }
    // log(`arr1, arr2 =`, arr1, arr2);
    let l = arr2.length - arr1.length;
    for (let i = 0; i < l; i++) {
      arr1.push(`0`);
    }
    // log(`✅ arr1, arr2 =`, arr1, arr2);
    // 不可以改变元数组的顺序 ✅
    // ???
    // log(`❌ a1, a2 =`, a1, a2);
    // 数组,引用类型 bug
    return a1.length < a2.length ? [arr1.map(i => removePrevZeros(i)), arr2.map(i => removePrevZeros(i))] : [arr2.map(i => removePrevZeros(i)), arr1.map(i => removePrevZeros(i))];
  }
  // log(`❌ a1, a2 =`, a1, a2);
  let [arr1, arr2] = autoAlignArray(a1, a2);
  // log(`❌ arr1, arr2 =`, arr1, arr2);
  // . 修订号数量对齐
  for (let i = 0; i < arr1.length; i++) {
    if(parseInt(arr1[i]) > parseInt(arr2[i])) {
      return 1;
    }
    if(parseInt(arr1[i]) < parseInt(arr2[i])) {
      return -1;
    }
  }
  return 0;
};


// 测试用例 test cases
const testCases = [
  {
    inputs: ["1.01", "1.001"],
    result: 0,
    desc: 'value equal to 0',
  },
  {
    inputs: ["1.0", "1.0.0"],
    result: 0,
    desc: 'value equal to 0',
  },
  {
    inputs: ["0.1", "1.1"],
    result: -1,
    desc: 'value equal to -1',
  },
  {
    inputs: ["1.0.1", "1"],
    result: 1,
    desc: 'value equal to 1',
  },
  {
    inputs: ["1", "1.1"],
    result: -1,
    desc: 'value equal to -1',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const [first, second] = testCase.inputs;
  const result = compareVersion(first, second);
  log(`test case ${i} result: `, result === testCase.result ? `✅ passed` : `❌ failed`, result);
}


// $ npx ts-node ./165\ compare-version-numbers.ts

/*

test case 0 result:  ✅ passed 0
test case 1 result:  ✅ passed 0
test case 2 result:  ✅ passed -1
test case 3 result:  ✅ passed 1
test case 4 result:  ✅ passed -1

*/


image



(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-03-03 20:23  xgqfrms  阅读(938)  评论(3编辑  收藏  举报