1

I need to generate something like A, B, C, D, E, ..., X, Y, Z, AA, AB, AC, ....

So from 1 up to n (n being a random integer).

How can this be done in JavaScript? Is there maybe a library that already does this?

melpomene
  • 84,125
  • 8
  • 85
  • 148
daniels
  • 18,416
  • 31
  • 103
  • 173

1 Answers1

2

Here is an option adapted from one of the answers in this Code Review question. The crux of this approach is we recognize your desired sequence as essentially being a base 26 type digit. By base 26, I mean that every time the "tens" digit cycles through 26 letters, we increment the letter to the left by one (and so on for the other positions). So we can simply iterate over the input number and determine the letter for each position in the output.

function IntToLetters(value) {
    var result = '';

    while (--value >= 0) {
        result = String.fromCharCode(65 + value % 26 ) + result;
        value /= 26;
    }
    return result;
}

console.log(IntToLetters(26));
console.log(IntToLetters(27));
console.log(IntToLetters(53));
console.log(IntToLetters(1000));
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Looks like there's an extra `var` at the start of line #5. Other than this works as needed. Thank you. – daniels Jan 06 '18 at 14:17