roman: check number range

This commit is contained in:
vinchent 2024-09-22 22:00:50 +02:00
parent abc546178d
commit 8629b537b0
2 changed files with 15 additions and 6 deletions

View File

@ -1,6 +1,9 @@
package roman package roman
import "strings" import (
"errors"
"strings"
)
type RomanNumeral struct { type RomanNumeral struct {
Value uint16 Value uint16
@ -24,7 +27,12 @@ var allRomanNumerals = []RomanNumeral{
{1, "I"}, {1, "I"},
} }
func ConvertToRoman(arabic uint16) string { var ErrNumberOutOfRange = errors.New("numbers should not be bigger than 3999")
func ConvertToRoman(arabic uint16) (string, error) {
if arabic > 3999 {
return "", ErrNumberOutOfRange
}
var converted strings.Builder var converted strings.Builder
for _, numeral := range allRomanNumerals { for _, numeral := range allRomanNumerals {
for arabic >= numeral.Value { for arabic >= numeral.Value {
@ -33,9 +41,10 @@ func ConvertToRoman(arabic uint16) string {
} }
} }
return converted.String() return converted.String(), nil
} }
// XXX: This convert function doesn't check the validity of the roman numerals string
func ConvertToArabic(roman string) uint16 { func ConvertToArabic(roman string) uint16 {
var converted uint16 var converted uint16
for _, numeral := range allRomanNumerals { for _, numeral := range allRomanNumerals {

View File

@ -44,7 +44,7 @@ var cases = []struct {
func TestRomanNemerals(t *testing.T) { func TestRomanNemerals(t *testing.T) {
for _, test := range cases { for _, test := range cases {
t.Run(fmt.Sprintf("%d gets converted to %q", test.Arabic, test.Roman), func(t *testing.T) { t.Run(fmt.Sprintf("%d gets converted to %q", test.Arabic, test.Roman), func(t *testing.T) {
got := ConvertToRoman(test.Arabic) got, _ := ConvertToRoman(test.Arabic)
want := test.Roman want := test.Roman
if got != want { if got != want {
@ -69,10 +69,10 @@ func TestConvertingToArabic(t *testing.T) {
func TestPropertiesOfConversion(t *testing.T) { func TestPropertiesOfConversion(t *testing.T) {
assertion := func(arabic uint16) bool { assertion := func(arabic uint16) bool {
roman, err := ConvertToRoman(arabic)
if arabic > 3999 { if arabic > 3999 {
return true return err == ErrNumberOutOfRange
} }
roman := ConvertToRoman(arabic)
fromRoman := ConvertToArabic(roman) fromRoman := ConvertToArabic(roman)
return fromRoman == arabic return fromRoman == arabic
} }