Skip to content
Permalink
Browse files

Refactor toRoman function

Repetition of the decreasing powers of ten suggested a refactor.
This called for an additional function to map a base unit (power of ten)
to its single-character Roman symbol.
  • Loading branch information
michaelbannister committed Jul 3, 2016
1 parent 0d7e4fa commit b52d09d0bbd81dc8013d6c1d9157bba74634b42f
Showing with 19 additions and 9 deletions.
  1. +19 −9 src/main/kotlin/RomanNumerals.kt
@@ -1,11 +1,21 @@
fun Int.toRoman(): String {
if (this >= 1000) {
return "M".repeat(this / 1000)
} else if (this >= 100) {
return "C".repeat(this / 100)
} else if (this >= 10) {
return "X".repeat(this / 10)
} else {
return "I".repeat(this)
val powersOfTen = listOf(1000, 100, 10, 1)
powersOfTen.forEach { unit ->
if (this >= unit) {
return symbolFor(unit).repeat(this / unit)
}
}
}
throw RomanNumeralException("Can't yet convert ${this} to Roman numerals")
}

fun symbolFor(unit: Int): String {
return when(unit) {
1000 -> "M"
100 -> "C"
10 -> "X"
1 -> "I"
else -> throw RomanNumeralException("No mapping to symbol for ${unit}")
}
}

class RomanNumeralException(message: String) : RuntimeException(message)

0 comments on commit b52d09d

Please sign in to comment.
You can’t perform that action at this time.