dict: add update method

This commit is contained in:
vinchent 2024-09-17 11:31:00 +02:00
parent 4be80f4477
commit c04a2e1d65
2 changed files with 37 additions and 2 deletions

View File

@ -3,8 +3,9 @@ package dictionary
type Dictionary map[string]string
const (
ErrNotFound = DictionaryErr("could not find the word you were looking for")
ErrWordExists = DictionaryErr("word exists")
ErrNotFound = DictionaryErr("could not find the word you were looking for")
ErrWordExists = DictionaryErr("word exists")
ErrWordDoesNotExist = DictionaryErr("word does not exist")
)
type DictionaryErr string
@ -34,3 +35,16 @@ func (d Dictionary) Add(word, definition string) error {
}
return nil
}
func (d Dictionary) Update(word, definition string) error {
_, err := d.Search(word)
switch err {
case ErrNotFound:
return ErrWordDoesNotExist
case nil:
d[word] = definition
default:
return err
}
return nil
}

View File

@ -70,3 +70,24 @@ func TestAdd(t *testing.T) {
assertDefinition(t, dict, word, def)
})
}
func TestUpdate(t *testing.T) {
t.Run("update an existing word", func(t *testing.T) {
word := "test"
def := "this is just a test"
updated := "updated definition"
dict := Dictionary{word: def}
dict.Update(word, updated)
assertDefinition(t, dict, word, updated)
})
t.Run("update an non-existing word", func(t *testing.T) {
word := "test"
updated := "updated definition"
dict := Dictionary{}
err := dict.Update(word, updated)
assertError(t, err, ErrWordDoesNotExist)
})
}