Skip to content

Instantly share code, notes, and snippets.

@PhilomathJ
Last active April 1, 2021 14:25
Show Gist options
  • Select an option

  • Save PhilomathJ/33f0aa7089aab06d8ba272e9d715a090 to your computer and use it in GitHub Desktop.

Select an option

Save PhilomathJ/33f0aa7089aab06d8ba272e9d715a090 to your computer and use it in GitHub Desktop.
Converts a column index (in Excel or Google Sheets) to the letter equivalent
/**
* Recursively returns the letter combination corresponding to the column for the given index
* This is a more functional programming approach compared to the usual loop-based method
* Tested to column index out to one decillion
* @param {number} num Index to be converted
* @returns {string} Letter combination as column indicator
*/
const columnIndexToLetter = (num: number): string => {
return num <= 26
? String.fromCharCode((num === 0 ? 26 : num) + 64)
: columnIndexToLetter(Math.floor((num - 1) / 26)) + columnIndexToLetter(num % 26);
};
// Testing
const column: number = 28;
console.log('column', column);
const letter = columnIndexToLetter(column);
console.log('letter', letter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment