diff --git a/dictionary/dictionary.go b/dictionary/dictionary.go index b04ece0..a4f459f 100644 --- a/dictionary/dictionary.go +++ b/dictionary/dictionary.go @@ -1,10 +1,18 @@ package dictionary -import "errors" - 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) { result, ok := d[word] @@ -14,6 +22,15 @@ func (d Dictionary) Search(word string) (string, error) { return result, nil } -func (d Dictionary) Add(word, definition string) { - d[word] = definition +func (d Dictionary) Add(word, definition string) error { + _, err := d.Search(word) + switch err { + case ErrNotFound: + d[word] = definition + case nil: + return ErrWordExists + default: + return err + } + return nil } diff --git a/dictionary/dictionary_test.go b/dictionary/dictionary_test.go index 4e35081..ef17f33 100644 --- a/dictionary/dictionary_test.go +++ b/dictionary/dictionary_test.go @@ -50,11 +50,23 @@ func assertDefinition(t testing.TB, dict Dictionary, word, def string) { } func TestAdd(t *testing.T) { - dict := Dictionary{} + t.Run("new word", func(t *testing.T) { + dict := Dictionary{} - word := "test" - def := "this is just a test" + word := "test" + def := "this is just a test" - dict.Add(word, def) - assertDefinition(t, dict, word, def) + dict.Add(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) + }) }