Skip to content

Instantly share code, notes, and snippets.

@westc
Created January 10, 2025 15:28
Show Gist options
  • Save westc/60cf6f9e4739d257933c3618cdb4294b to your computer and use it in GitHub Desktop.
Save westc/60cf6f9e4739d257933c3618cdb4294b to your computer and use it in GitHub Desktop.
toAlphaNumber() - Converts a positive integer into an alphabetic representation, similar to ordered list lettering and Excel column naming.
/**
* Converts a positive integer into an alphabetic representation, similar to
* ordered list lettering and Excel column naming.
*
* @param {number} int
* The positive integer to convert. Non-integers will be floored.
* @param {boolean} [returnLowerCase=false]
* If `true`, returns lowercase letters (e.g., 'a', 'b', ...).
* If `false`, returns uppercase letters (e.g., 'A', 'B', ...).
* @returns {string}
* The alphabetic representation of the integer (e.g., 1 -> 'A', 28 -> 'AB').
*
* @throws {Error}
* Throws an error if the input integer is less than 1.
*
* @example
* toAlphaNumber(1); // Returns "A"
* toAlphaNumber(28); // Returns "AB"
* toAlphaNumber(28, true); // Returns "ab"
* toAlphaNumber(0); // Throws Error
*/
function toAlphaNumber(int, returnLowerCase=false) {
if (!(int > 0 && int === Math.floor(int))) {
throw new Error('Input must be a positive integer greater than 0.');
}
const ASCII_OFFSET = returnLowerCase ? 97 : 65; // 97 for 'a', 65 for 'A'
let result = '';
while (int > 0) {
result = String.fromCharCode(ASCII_OFFSET + (int - 1) % 26) + result;
int = Math.floor((int - 1) / 26); // Adjust for 1-indexing
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment