Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day174:versions 是一个项目的版本号列表,因多人维护,不规则,动手实现一个版本号处理函数 #990

Open
Genzhen opened this issue Nov 11, 2020 · 2 comments
Labels
JavaScript teach_tag 头条 company

Comments

@Genzhen
Copy link
Collaborator

Genzhen commented Nov 11, 2020

var versions = ["1.45.0", "1.5", "6", "3.3.3.3.3.3.3"];
// 要求从小到大排序,注意'1.45'比'1.5'大
function sortVersion(versions) {
  // TODO
}
// => ['1.5','1.45.0','3.3.3.3.3.3','6']

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案
欢迎大家在下方发表自己的优质见解
二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

@Genzhen Genzhen added JavaScript teach_tag 头条 company labels Nov 11, 2020
@GuoLizhi
Copy link

主要思路:将version打断成字符串数组,再进行排序,主要耗时点在于排序上

function sortVersion(versions = []) {
    // 先将versions按逗号打断
    versions = versions.map(version => {
        return version.split('.')
    })
    versions.sort((a, b) => {
        const lenA = a.length
        const lenB = b.length
        for (let i = 0; i < Math.max(lenA, lenB); i++) {
            a[i] = a[i] === undefined ? 0 : Number(a[i])
            b[i] = b[i] === undefined ? 0 : Number(b[i])
            if (a[i] !== b[i]) {
                return a[i] - b[i]
            }
        }
        return 1
    })
    return versions.map(version => version.join('.'))
}

@BingBlog
Copy link

function sortVersion(versions) {
    return versions.map(item => item.split('.'))
                .sort((a, b) => compare(a, b))
                .map(item => item.join('.'));

    function compare(a = [], b = []) {
        let minLength = a.length < b.length ? a.length : b.length; 

        for(let i = 0; i < minLength; i++) {
            if (a[i] > b[i]) {
                return 1;
            }
            return -1;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript teach_tag 头条 company
Projects
None yet
Development

No branches or pull requests

3 participants