题目描述
我在写业务代码时,经常遇到需要比较版本号的场景 ——
比如客户端的某个新功能,发布在版本 19.5.0。假设一个用户本地的客户端版本低于 19.5.0,那么 Ta 显然无法正常使用这个新的 feature,这个时候我们需要提醒 Ta 去升级客户端。
我们通过客户端提供的某些 JSBridge 方法,或者 navigator.userAgent
,很容易获取到本地客户端的版本号,这个时候,我们就需要拿本地的版本号和目标版本号进行比较,然后根据比较结果,进行后续的操作。
写代码啦
先说一下我的思路吧:
- 先把字符串
source
和target
使用分隔符'.'
拆分为两个数组sourceList
和targetList
,并把数组中的每一项转换为数字; - 比较两个数组的
sourceList.length
和targetList.length
,修订号个数较少的一方,少多少个,就在数组后面push
几个0
; - 从左到右依次比较两个数组中的修订号数字大小,如果中途比出大小,分别返回
1
和-1
,否则在最后返回0
。
/**
* @description 比较版本号
* @param {string} source 本地版本号
* @param {string} target 目标版本号
* @return {number} 比较结果
*/
const compareVersion = (source, target) => {
const sourceList = source.split('.').map(item => Number(item));
const targetList = target.split('.').map(item => Number(item));
const diffLength = sourceList.length - targetList.length;
// source 和 target 修订号个数不同,个数少的在后面补零
if (diffLength > 0) {
targetList.push(...new Array(diffLength).fill(0));
} else if (diffLength < 0) {
sourceList.push(...new Array(Math.abs(diffLength)).fill(0));
}
// 从左到右依次比较它们的修订号
for (let index = 0; index < sourceList.length; index += 1) {
if (sourceList[index] > targetList[index]) {
return 1;
} else if (sourceList[index] < targetList[index]) {
return -1;
}
}
return 0;
};
- 时间复杂度:O(max(m,n))
- 空间复杂度:O(m+n)
以上解法是我的第一反应,在我看来也是比较容易理解的一种方法。
欢迎留言讨论你心目中更好的解法~