Commit 30ca3f0
Changed files (2)
dictionary.go
@@ -1,12 +1,16 @@
package main
-import (
- "errors"
-)
-
type Dictionary map[string]string
+type DictionaryError string
+
+var (
+ ErrorNotFound = DictionaryError("could not find the word you were looking for")
+ ErrorWordExists = DictionaryError("cannot add word because it already exists")
+)
-var ErrorNotFound = errors.New("could not find the word you were looking for")
+func (e DictionaryError) Error() string {
+ return string(e)
+}
func (d Dictionary) Search(word string) (string, error) {
definition, ok := d[word]
@@ -17,6 +21,17 @@ func (d Dictionary) Search(word string) (string, error) {
return definition, 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 ErrorNotFound:
+ d[word] = definition
+ case nil:
+ return ErrorWordExists
+ default:
+ return err
+ }
+
+ return nil
}
dictionary_test.go
@@ -23,18 +23,25 @@ func TestSearch(t *testing.T) {
}
func TestAdd(t *testing.T) {
- dictionary := Dictionary{}
- dictionary.Add("test", "this is just a test")
+ t.Run("new word", func(t *testing.T) {
+ dictionary := Dictionary{}
+ key := "test"
+ value := "this is just a test"
+ err := dictionary.Add(key, value)
- want := "this is just a test"
- got, err := dictionary.Search("test")
- if err != nil {
- t.Fatal("should find added word:", err)
- }
+ assertNil(t, err)
+ assertDefinition(t, dictionary, key, value)
+ })
- if want != got {
- t.Errorf("got %q want %q", got, want)
- }
+ t.Run("existing word", func(t *testing.T) {
+ key := "test"
+ value := "this is just a test"
+ dictionary := Dictionary{key: value}
+ err := dictionary.Add(key, "new test")
+
+ assertError(t, err, ErrorWordExists)
+ assertDefinition(t, dictionary, key, value)
+ })
}
func assertStrings(t *testing.T, got, want string) {
@@ -44,3 +51,22 @@ func assertStrings(t *testing.T, got, want string) {
t.Errorf("got %q want %q", got, want)
}
}
+
+func assertDefinition(t *testing.T, dictionary Dictionary, key, expected string) {
+ t.Helper()
+
+ actual, err := dictionary.Search("test")
+ if err != nil {
+ t.Fatal("should find added key:", err)
+ }
+
+ if expected != actual {
+ t.Errorf("actual %q want %q", actual, expected)
+ }
+}
+
+func assertNil(t *testing.T, actual error) {
+ if actual != nil {
+ t.Errorf("expected nil got %q", actual)
+ }
+}