Created
January 28, 2019 15:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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