-2

A function to return the next character. For example, given A, the next letter should be B.

say you wanted to name a list of items using letters ... you'd start with A, B ... Z. But after Z you want to start at AA, AB, AC ... AZ. Which would go in to BA, BB, BC ... BZ. When you get to ZZ you want to start at AAA

A -> B
B -> C
Z -> AA
AA -> AB
AB -> AC
AZ -> BA
BA -> BB
ZZ -> AAA

What I started with was a function to get the next character until Z

const nextLetter = (char) => {
 return char === 'Z' ? 'A': String.fromCharCode(char.charCodeAt(0) + 1);
}

console.log(nextLetter('A'))
console.log(nextLetter('G'))
console.log(nextLetter('Z'))

But later I came up with a solution that I thought I'd share with the world, that can either be improved on or made more efficient.

Link to the first solution

Njeri Ngigi
  • 515
  • 5
  • 15
  • 5
    Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). – Federico klez Culloca Mar 06 '19 at 11:58
  • 1
    What did you try? – mstfyldz Mar 06 '19 at 11:58
  • ..and finally take a look into [mcve] and feel free to edit the post, thanks – xxxvodnikxxx Mar 06 '19 at 11:58
  • How does `Z -> AA`, `AZ -> BA` and `ZZ -> AAA` fit in the same logic? It is like a jigsaw to me. – vahdet Mar 06 '19 at 11:58
  • @vahdet: This is the precise semantics of `++` on a string in Perl, PHP and Ruby. – Amadan Mar 06 '19 at 11:59
  • Possible duplicate of [Implement numbering scheme like A,B,C… AA,AB,… AAA…, similar to converting a number to radix26](https://stackoverflow.com/questions/12699030/implement-numbering-scheme-like-a-b-c-aa-ab-aaa-similar-to-converting-a-num) and [Convert numbers to letters beyond the 26 character alphabet](https://stackoverflow.com/questions/8240637) – adiga Mar 06 '19 at 12:00
  • say you wanted to name a list of items using letters ... you'd start with A, B ... Z. But after Z you want to start at AA, AB, AC ... AZ. Which would go in to BA, BB, BC ... BZ. When you get to ZZ you want to start at AAA @vahdet – Njeri Ngigi Mar 06 '19 at 12:04
  • @mstfyldz ... it took me a while to find the solution to this problem. When I couldn't find one, I created a function to do this myself. Its the first solution posted – Njeri Ngigi Mar 06 '19 at 12:06
  • Ok, but next time you want to answer your own question, use the appropriate checkbox in the question form, so that you can post both the question and the answer together and it's clear that you're doing this for documentation purpose. Also, the fact that you're answering your own question doesn't dispense you from writing a good question to begin with :) – Federico klez Culloca Mar 06 '19 at 12:17
  • good to know @FedericoklezCulloca ... edited it – Njeri Ngigi Mar 06 '19 at 12:20

3 Answers3

4

The function incrementChar() will always return the next letter or string of letters.

const nextLetter = (char) => {
 return char === 'Z' ? 'A': String.fromCharCode(char.charCodeAt(0) + 1);
}

let newCharArray = [];

const incrementChar = (l) => {
  const lastChar = l[l.length - 1]
  const remString = l.slice(0, l.length - 1)
  const newChar = lastChar === undefined ? 'A' : nextLetter(lastChar);
  newCharArray.unshift(newChar)

  if (lastChar === 'Z') {
    return incrementChar(remString)
  } 
  const batchString = remString + [...newCharArray].join('')
  newCharArray = []
  return batchString;
}

console.log(incrementChar(''))
console.log(incrementChar('A'))
console.log(incrementChar('AZ'))
console.log(incrementChar('BZ'))
console.log(incrementChar('ZZ'))
console.log(incrementChar('CAZ'))
console.log(incrementChar('DZZ'))
console.log(incrementChar('ZZZZ'))
Njeri Ngigi
  • 515
  • 5
  • 15
2

You could use two dedicated functions for getting the numerical value or the letter value.

function getValue(s) {
    return s.split('').reduce((r, a) => r * 26 + parseInt(a, 36) - 9, 0) - 1;
}

function setValue(n) {
    var result = '';
    do {
        result = (n % 26 + 10).toString(36) + result;
        n = Math.floor(n / 26) - 1;
    } while (n >= 0)
    return result.toUpperCase();
}

function incrementChar(string) {
    return setValue(getValue(string) + 1);
}

console.log(incrementChar(''));
console.log(incrementChar('A'));
console.log(incrementChar('AZ'));
console.log(incrementChar('BZ'));
console.log(incrementChar('ZZ'));
console.log(incrementChar('CAZ'));
console.log(incrementChar('DZZ'));
console.log(incrementChar('ZZZZ'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

This is my function to get increment letters to infinity in Javascript( for uppercase only)

function getNextStringId(str) {
    let index = str.length-1;
    let baseCode= str.charCodeAt(index);
    do{
        baseCode= str.charCodeAt(index);
        let strArr= str.split("");
        if(strArr[index] == "Z"){
            strArr[index] = "A";
            if(index==0){
                strArr.unshift("A");
            }
        }
        else{
            strArr[index]= String.fromCharCode(baseCode + 1);
        }
        str= strArr.join("");
        index--;
    } while(baseCode == 90)
    return str;
}


getNextStringId("A") // B
getNextStringId("Z") // AA
getNextStringId("ABZZ") // ACAA
Manoj Rana
  • 3,068
  • 1
  • 24
  • 34