Groovy web console

subscribe to the feed Subscribe
to this
site

Integer Metaclass toRoman()

Published 1 month ago by Marcello de Sales with tags integer metaclass roman
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def part(number, digit) {
  return (long)(number % (digit * 10) / digit)
}

def toRoman(number) {
  def ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
  def tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "LC"]
  def hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
  def thousands = ["", "M", "MM", "MMM"]

  return thousands[part(number, 1000)] + hundreds[part(number, 100)] + 
      tens[part(number, 10)] + ones[part(number, 1)]
}

// https://www.tothenew.com/blog/metaprogramming-with-metaclass/
Integer.metaClass.toRoman = { -> // only (->) sign indicates that isEven() method is no argument method     
  toRoman(delegate)
}

println 1040.toRoman()
println 2368.toRoman()
println 3978.toRoman()