Tiny Recursions I

I just wanted to figure out whether I could do this quickly: Mapping Hindu-Arabic numerals to their Roman equivalents.

I’ve come up with a easy to read recursive solution:

# file: "to-roman.coffee"
@toRoman = (num) ->
  if num >= 1000 then "M" + toRoman(num - 1000)
  else if num >= 900 then "CM" + toRoman(num - 900)
  else if num >= 500 then "D" + toRoman(num - 500)
  else if num >= 400 then "CD" + toRoman(num - 400)
  else if num >= 100 then "C" + toRoman(num - 100)
  else if num >= 90 then "XC" + toRoman(num - 90)
  else if num >= 50 then "L" + toRoman(num - 50)
  else if num >= 40 then "XL" + toRoman(num - 40)
  else if num >= 10 then "X" + toRoman(num - 10)
  else if num == 9 then "IX" + toRoman(num - 9)
  else if num >= 5 then "V" + toRoman(num - 5)
  else if num == 4 then "IV" + toRoman(num - 4)
  else if num >= 1 then "I" + toRoman(num - 1)
  else ""

© 2024 Florian Klampfer

Powered by Hydejack v9.2.0