Skip to content

Instantly share code, notes, and snippets.

@ngehlert
Created January 28, 2019 15:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ngehlert/387cb22c66cb1185b0aaaa202da7841e to your computer and use it in GitHub Desktop.
Helper function to create Excel-column-like alphabet sorting values; e.g. 1 --> A, 2 --> B, 27 --> AA, 28 --> AB, etc
function numberToLetters(index: number): string {
const charLimit: number = 26;
if (index > charLimit) {
if (index % charLimit === 0) {
return `${numberToLetters((index / charLimit) - 1)}${numberToLetters(charLimit)}`;
} else {
return `${numberToLetters(Math.trunc(index / charLimit))}${numberToLetters(index % charLimit)}`;
}
} else {
const a: number = 'A'.charCodeAt(0);
return String.fromCharCode(a + index - 1);
}
}
// Or if needed without TypeScript or ES6 template strings
function numberToLetters(index) {
var charLimit = 26;
if (index > charLimit) {
if (index % charLimit === 0) {
return '' + numberToLetters((index / charLimit) - 1) + numberToLetters(charLimit);
} else {
return '' + numberToLetters(Math.trunc(index / charLimit)) + numberToLetters(index % charLimit);
}
} else {
var a = 'A'.charCodeAt(0);
return String.fromCharCode(a + index - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment