使用 Typescript 对多个版本号序列排序

2022-03-22 15:43:48 浏览数 (1)

  • 作者:约克
  • 原文地址:https://yorkyu.cn/use-ts-to-sort-multiple-version-numbers-1b104f681262.html
  • 文章版权归作者所有,转载请注明出处!

版本号排序

例如现在存在一组版本号,[{version: "0.12.0.2"}, {version: "0.1.0.2"}],按 version 排序后的结果为 [{version: "0.1.0.2"}, {version: "0.12.0.2"}]

代码语言:javascript复制
interface Src {
	version: string;
	system: iOS | Android;
	name: string;
}

function versionSort(src: Src[] = [], orderKey?: string = 'version'): Src[] {
  return src.sort((a, b) => {
      let i = 0;
      let arrA = [];
      let arrB = [];

      const aType = typeof a;
      const bType = typeof b;
      if (aType !== bType) {
        return;
      }

      if (aType === 'object') {
        arrA = a[orderKey].split('.');
        arrB = b[orderKey].split('.');
      }

      while (true) {
          const sA = arrA[i];
          const sB = arrB[i  ];

          if (sA === undefined || sB === undefined) {
              return arrB.length - arrA.length;
          }

          if (sA === sB) continue;

          return sB - sA;
      }
  });
}

const data: Src[] = [
	{
		version: '0.12.0.2',
		system: 'iOS',
		name: 'v0.12.0.2',
	},
	{
		version: '1.12.2.2',
		system: 'iOS',
		name: 'v1.12.2.2',
	},
	{
		version: '0.15.78',
		system: 'iOS',
		name: 'v0.15.78',
	},
	{
		version: '0.10.78',
		system: 'iOS',
		name: 'v0.10.78',
	}
];

console.log(versionSort(data));

参考

  • [1] js判断对多个版本号进行排序怎么做?

0 人点赞