I want to convert an integer into its character equivalent based on the alphabet. For example:
0 => a
1 => b
2 => c
3 => d
etc.
The only problemo with @mikemaccana's great solution is that it uses the binary >> operator which is costly, performance-wise. I suggest this modification to his great work as a slight improvement that your colleagues can perhaps read more easily.
const getColumnName = (i) => {
const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
return previousLetters + lastLetter;
}
Or as a one-liner
const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];
Example:
getColumnName(0); // "A"
getColumnName(1); // "B"
getColumnName(25); // "Z"
getColumnName(26); // "AA"
getColumnName(27); // "AB"
getColumnName(80085) // "DNLF"