dict: deal with re-add

This commit is contained in:
vinchent 2024-09-17 10:19:25 +02:00
parent 58efd33b20
commit 4be80f4477
2 changed files with 39 additions and 10 deletions

View File

@ -1,10 +1,18 @@
package dictionary package dictionary
import "errors"
type Dictionary map[string]string type Dictionary map[string]string
var ErrNotFound = errors.New("could not find the word you were looking for") const (
ErrNotFound = DictionaryErr("could not find the word you were looking for")
ErrWordExists = DictionaryErr("word exists")
)
type DictionaryErr string
// implements the Error interface, makes it an "error"
func (e DictionaryErr) Error() string {
return string(e)
}
func (d Dictionary) Search(word string) (string, error) { func (d Dictionary) Search(word string) (string, error) {
result, ok := d[word] result, ok := d[word]
@ -14,6 +22,15 @@ func (d Dictionary) Search(word string) (string, error) {
return result, nil return result, nil
} }
func (d Dictionary) Add(word, definition string) { func (d Dictionary) Add(word, definition string) error {
_, err := d.Search(word)
switch err {
case ErrNotFound:
d[word] = definition d[word] = definition
case nil:
return ErrWordExists
default:
return err
}
return nil
} }

View File

@ -50,6 +50,7 @@ func assertDefinition(t testing.TB, dict Dictionary, word, def string) {
} }
func TestAdd(t *testing.T) { func TestAdd(t *testing.T) {
t.Run("new word", func(t *testing.T) {
dict := Dictionary{} dict := Dictionary{}
word := "test" word := "test"
@ -57,4 +58,15 @@ func TestAdd(t *testing.T) {
dict.Add(word, def) dict.Add(word, def)
assertDefinition(t, dict, word, def) assertDefinition(t, dict, word, def)
})
t.Run("existing word", func(t *testing.T) {
word := "test"
def := "this is just a test"
dict := Dictionary{word: def}
err := dict.Add(word, def)
assertError(t, err, ErrWordExists)
assertDefinition(t, dict, word, def)
})
} }