Skip to content

Commit

Permalink
Refactor toRoman function
Browse files Browse the repository at this point in the history
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 b52d09d
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions 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.