1

What I want is a function that takes in input a number and returns an alphabet letter (a-z).

This is my code (I get it from this question):

function numberToLetter(value) {
  const roundedPositiveValue = Math.round(Math.abs(value))
  return (roundedPositiveValue + 9).toString(36)
  // return ((roundedPositiveValue % 26) + 9).toString(36)
}

function print(value) {
  document.write(`${value} → ${numberToLetter(value)}<br>`)
}

[-10, -2, 0, 2.5, 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, 200].forEach(v => print(v))

It works but not in every case. For example it doesn't work for values > 26, so I tried using the modulo operator but in that case (commented line), it doesn't work for value 26. How can I fix it?

whitecircle
  • 237
  • 9
  • 34

1 Answers1

3

You could subtract one, to get a zero based value, apply modulo and add one to get values from one to 26.

function numberToLetter(value) {
    const adjusted = ((Math.round(Math.abs(value)) - 1) % 26) + 1;
    return (adjusted + 9).toString(36);
}

function print(value) {
    document.write(`${value} → ${numberToLetter(value)}<br>`)
}

[-10, -2, 0, 2.5, 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, 200].forEach(v => print(v))
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392