Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function to compare two versions

Im writting a function to compare 2 versions, and return true if the second is bigger then first version.

but my algorithm have a "hole", and I cant figure out how fix.

function compareversion(version1,version2){

    var result=false;

    if(typeof version1!=='object'){ version1=version1.toString().split('.'); }
    if(typeof version2!=='object'){ version2=version2.toString().split('.'); }

    for(var i=0;i<(Math.max(version1.length,version2.length));i++){

        if(version1[i]==undefined){ version1[i]=0; }
        if(version2[i]==undefined){ version2[i]=0; }

        if(version1[i]<version2[i]){
            result=true;
            break;
        }
    }
    return(result);
}

this exemples return as expected

compareversion('1','1') //false
compareversion('1','1.0.0') //false
compareversion('2.0','1.0.0') //false
compareversion('1.1','1.2') //true
compareversion('1','1.0.0.1') //true

but this

compareversion('1.1.0','1.0.1') //return true but should be false
like image 994
Vitim.us Avatar asked Dec 09 '22 05:12

Vitim.us


2 Answers

This should work:

function compareversion(version1,version2){

    var result=false;

    if(typeof version1!=='object'){ version1=version1.toString().split('.'); }
    if(typeof version2!=='object'){ version2=version2.toString().split('.'); }

    for(var i=0;i<(Math.max(version1.length,version2.length));i++){

        if(version1[i]==undefined){ version1[i]=0; }
        if(version2[i]==undefined){ version2[i]=0; }

        if(Number(version1[i])<Number(version2[i])){
            result=true;
            break;
        }
        if(version1[i]!=version2[i]){
            break;
        }
    }
    return(result);
}

The reason compareversion('1.1.0','1.0.1') fails is that your code first compares 1 to 1, then 1 to 0 (it does not break here since it only breaks if version1[i] < version2[i]) and then 0 to 1.

Since 0 < 1, it returns false.

like image 73
Dennis Avatar answered Jan 01 '23 09:01

Dennis


If version1 is at that index bigger, you know it should return false. You only need to continue if they are equal.

    if(version1[i]<version2[i]){
        result=true;
        break;
    }

    if(version1[i]>version2[i]){
        result=false;
        break;
    }

    // Will only get here if both are equal, in all other
    // cases you broke out of the loop. So only continue
    // checking the next index when this one was equal.
like image 25
pimvdb Avatar answered Jan 01 '23 09:01

pimvdb