forked from properdom/tddWorkshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
1 parent
0d7e4fa
commit b52d09d
Showing
1 changed file
with
19 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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) |