Last active
January 27, 2021 02:55
-
-
Save djrosenbaum/248d8f88cf19256b280679849bfd6227 to your computer and use it in GitHub Desktop.
incrementally convert from numbers to letters or from letters to number
This file contains hidden or 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
/* | |
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