All files number-to-letter.ts

100% Statements 17/17
100% Branches 2/2
100% Functions 1/1
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411x 1x     1x                                       1x 10x 10x 10x 10x 10x 10x   10x 21x 21x 21x 10x   10x 10x  
import { floor } from './floor.ts';
import { empty } from './unicode.ts';
 
// eslint-disable-next-line no-secrets/no-secrets
const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 
/**
 * Options for the {@link numberToLetter} function
 * @group String
 * @category Operations
 */
export type NumberToLetterOptions = {
  /** The alphabet to use */
  alphabet?: string;
};
 
/**
 * Convert a number to a letter, using the alphabet (default: A-Z)
 * @param num - The number to convert
 * @param options - see {@link NumberToLetterOptions}
 * @returns The letter
 * @group String
 * @category Operations
 */
export function numberToLetter(
  num: number,
  { alphabet = ALPHABET }: NumberToLetterOptions = {},
): string {
  let n = num;
  const base = alphabet.length;
  const letters: string[] = [];
 
  do {
    --n;
    letters.unshift(alphabet[n % base]);
    n = floor(n / base, { tolerance: 0.005 });
  } while (n > 0);
 
  return letters.join(empty);
}