Search code examples
javascriptregexfunctionrevision

How to use javascript to calculate the next revision number


I have a revision number attribute in my application and it is simply a string. i need to pass in the current value and calculate the next valid one and return that.

Here is the valid progression:

.A
.B
.C
0
0.A
0.B
1
1.A
etc

Forget the whole numbers, that is controlled elsewhere. This deals with only the ones with periods. The restrictions are:

  • The first component is always a number (or nothing)
  • Then a period
  • Then a letter, excluding I and O (since they resemble 1 and 0) and once you reach Z it should go to AA, AB, AC, ..., ZZ

So

If I pass in .A it should return .B
If I pass in 1.H it should pass back 1.J
If I pass in 1.Z it should pass back 1.AA

Any help would be appreciated.

Here's what I have - I just don't know how to "increment" the letter portion:

function calcNextRev(currentRev)
{
var revParts = currentRev.split(".");
var majorRev = revParts[0];
var currentMinorRev = revParts[1];

???

return majorRev + "." + newMinorRev;
}

Solution

  • Try this:

    (demo here)

    var alfab = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z']; var currentRev = '0.AZ'; var result;

    function calcNextRev(currentRev) {
    var newMinorRev;
    var revParts = currentRev.split(".");
    var majorRev = revParts[0];
    var currentMinorRev = revParts[1];
    //Case string is 1 letter long
    if (currentMinorRev.length == 1) {
        for (i = 0; i < alfab.length; i++) {
            if (currentMinorRev == alfab[i]) {
                if (i == alfab.length - 1) {
                    newMinorRev = alfab[0] + alfab[0];
                } else {
                    var ii = i + 1;
                    newMinorRev = alfab[ii];
                }
            }
        }
    }
    //Case string is more than one letter long
    if (currentMinorRev.length > 1) {
        var currentMinorRev2 = currentMinorRev.split("");
        var l = currentMinorRev2.length - 1;
        for (o = 0; o < alfab.length; o++) {
            if (currentMinorRev2[l] == alfab[o] && o == alfab.length - 1) 
            {
                var currentalias = currentMinorRev2;
                currentalias[l] = alfab[0];
                currentalias.push(alfab[0]);
                newMinorRev = currentalias.join('');
            } 
            if (currentMinorRev2[l] == alfab[o] && o != alfab.length - 1) 
            {
                var xo = o + 1;
                var currentalias = currentMinorRev2;
                currentalias[l] = alfab[xo];
                newMinorRev = currentalias.join('');
                o++;
    
            }
        }
    };
    result = majorRev + "." + newMinorRev;
    return result;
    }
    
    alert(calcNextRev(currentRev));