javascriptcountingletters

JS: How to count in letters


I want to be able to count in base 26, but only with the letters of the alphabet.

I can cover the basics like A + 1 = B and Z + 1 = AA, but i want it to work for very long "numbers" like AZZEBERBZZ

Currently i have the following code in JavaScript

function getNextColumn(currentColumn) {
    currentColumn = currentColumn.toUpperCase();
    let lastLetterCode = currentColumn.charCodeAt(currentColumn.length - 1);

    if(lastLetterCode < 90) {
        return currentColumn.slice(0, -1) + String.fromCharCode(lastLetterCode + 1);
    } else {
        return currentColumn.slice(0, -1) + "A";
    }
}

But the issue here is that when i'm at AZ it just returns AAA instead of BA

How can i solve this?

EXTRA CONTEXT:

I need the function getNextColumn because I use this function to loop over an object created from an excel sheet, where to columns are counted in base26 but only with letters and no numbers


Solution

  • This is a perfect candidate to use a recursive function.

    With a recursive function you need to define a base situation and a recursive situation.

    You already covered the base situations, which are 2 situations in this case:

    In all other cases you have the "recursive situation" where your input:

    For this "recursive situation" you can trim the last "Z" (because you need to replace it with an "A" anyway) and then recall this function again, like so:

    function getNextColumn(currentColumn) {
        currentColumn = currentColumn.toUpperCase();
        let lastLetterCode = currentColumn.charCodeAt(currentColumn.length - 1);
    
        if(currentColumn === "Z"){
            return "AA";
        }
    
        if(lastLetterCode < 90) {
            return currentColumn.slice(0, -1) + String.fromCharCode(lastLetterCode + 1);
        }
    
        return getNextColumn(currentColumn.slice(0, -1)) + "A";
    }