Skip to content

Instantly share code, notes, and snippets.

@djrosenbaum
Last active January 27, 2021 02:55
Show Gist options
  • Save djrosenbaum/248d8f88cf19256b280679849bfd6227 to your computer and use it in GitHub Desktop.
Save djrosenbaum/248d8f88cf19256b280679849bfd6227 to your computer and use it in GitHub Desktop.
incrementally convert from numbers to letters or from letters to number
/*
These javascript functions allow for converting from numbers to letters or from letters to number
I am using these functions to increment channels in a firebase realtime db using numbers as letters
going beyond 26 letters in the alphabet
For example 0 => A or 26 => AA similar to spreadsheet naming
numberToLetters(123) => "DT"
lettersToNumber('DT') => 123
*/
/**
* Converts a number to letters
*
* @param { Number } num - some number
* @returns { string } - a string representing the number. for example 123 will return "DT"
*/
function numberToLetters(num) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const base = alphabet.length;
let letters = '';
while (num >= 0) {
letters = alphabet[num % base] + letters;
num = Math.floor(num / base) - 1;
}
return letters;
}
/**
* Convert letters to a number
*
* @param { string } letters - some letters
* @returns { Number } - a number representing the letters. for example "DT" will return 123
*/
function lettersToNumber(letters) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const base = alphabet.length;
let num = 0;
letters.split('').reverse().forEach((letter, index) => {
const letterIndex = alphabet.indexOf(letter);
if (index === 0) {
num += letterIndex;
} else {
num += Math.pow(base, index) * (letterIndex + 1);
}
});
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment