Skip to content

Commit

Permalink
Finished CRUD API development for the dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
vedicpanda committed May 31, 2023
1 parent 2cdf039 commit a87cdea
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
24 changes: 22 additions & 2 deletions Maps/dictionary.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions Maps/dictionary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit a87cdea

Please sign in to comment.