From a87cdea5f447e0c0f15ff74700f5eb5128d3bbbb Mon Sep 17 00:00:00 2001 From: Vedic Date: Wed, 31 May 2023 10:43:26 -0500 Subject: [PATCH] Finished CRUD API development for the dictionary --- Maps/dictionary.go | 24 ++++++++++++++++++++++-- Maps/dictionary_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/Maps/dictionary.go b/Maps/dictionary.go index f61a234..142c8f6 100644 --- a/Maps/dictionary.go +++ b/Maps/dictionary.go @@ -1,8 +1,9 @@ package dictionary const ( - ErrNotFound = DictionaryErr("could not find the word you were looking for") - ErrWordExists = DictionaryErr("cannot add word because it already exists") + ErrNotFound = DictionaryErr("could not find the word you were looking for") + ErrWordExists = DictionaryErr("cannot add word because it already exists") + ErrWordDoesNotExist = DictionaryErr("cannot update word because it does not exist") ) type DictionaryErr string @@ -37,6 +38,25 @@ 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 +} + +func (d Dictionary) Delete(word string) { + delete(d, word) +} + //a map value is a pointer to a hmap structure meaning that when you pass in a map to a function/method you are only copying the pointer address part, which means that you can modify its underlying data! //you can't create a nil map and then write into it without causing a run time error: looks like this -> var m map[string]string diff --git a/Maps/dictionary_test.go b/Maps/dictionary_test.go index 20e76a0..3a3ba8b 100644 --- a/Maps/dictionary_test.go +++ b/Maps/dictionary_test.go @@ -69,3 +69,39 @@ func assertDefinition(t testing.TB, dictionary Dictionary, word, definition stri } assertStrings(t, got, definition) } + +func TestUpdate(t *testing.T) { + t.Run("existing word", func(t *testing.T) { + word := "test" + definition := "this is just a test" + dictionary := Dictionary{word: definition} + newDefinition := "new definition" + + err := dictionary.Update(word, newDefinition) + + assertError(t, err, nil) + assertDefinition(t, dictionary, word, newDefinition) + }) + + t.Run("new word", func(t *testing.T) { + word := "test" + definition := "this is just a test" + dictionary := Dictionary{} + + err := dictionary.Update(word, definition) + + assertError(t, err, ErrWordDoesNotExist) + }) +} + +func TestDelete(t *testing.T) { + word := "test" + dictionary := Dictionary{word: "test definition"} + + dictionary.Delete(word) + + _, err := dictionary.Search(word) + if err != ErrNotFound { + t.Errorf("Expected %q to be deleted", word) + } +}