NumToChar & CharToNum
Example Usage : Excel Sheet Calculation.
/**
* Number to Character Util
* @param { string } num
* @returns { string } Character String
*/
export const numberToChar = (num: number): string => {
const division = Math.floor(num / 26)
const remainder = Math.floor(num % 26)
const char = String.fromCharCode(remainder + 97).toUpperCase()
return division - 1 >= 0 ? numberToChar(division - 1) + char : char
}
/**
* Character to Number
* @param { string } letters
*/
export const characterToNumber = (letters: string): void => {
letters
// Get each Letter on it own
.split('')
// Smaller First and then Bigger
.reverse()
// Convert them to base 26 numbers
.map((letter, idx) =>
idx === 0
? letter.toLowerCase().charCodeAt(0) - 97
: // The addition of 1 here is to oppose what we die for numberToChar
letter.toLowerCase().charCodeAt(0) - 97 + 1
)
// Convert base 26 to base 10
.map((base26Number, position) => base26Number * 26 ** position)
// Sum
.reduce((sum: number, number: number) => sum + number, 0)
}