From c04a2e1d652bd8ea0896a02b31c2c7d33724d7a6 Mon Sep 17 00:00:00 2001 From: vinchent Date: Tue, 17 Sep 2024 11:31:00 +0200 Subject: [PATCH] dict: add update method --- dictionary/dictionary.go | 18 ++++++++++++++++-- dictionary/dictionary_test.go | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/dictionary/dictionary.go b/dictionary/dictionary.go index a4f459f..fc374f3 100644 --- a/dictionary/dictionary.go +++ b/dictionary/dictionary.go @@ -3,8 +3,9 @@ package dictionary type Dictionary map[string]string const ( - ErrNotFound = DictionaryErr("could not find the word you were looking for") - ErrWordExists = DictionaryErr("word exists") + ErrNotFound = DictionaryErr("could not find the word you were looking for") + ErrWordExists = DictionaryErr("word exists") + ErrWordDoesNotExist = DictionaryErr("word does not exist") ) type DictionaryErr string @@ -34,3 +35,16 @@ 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 +} diff --git a/dictionary/dictionary_test.go b/dictionary/dictionary_test.go index ef17f33..c9a3968 100644 --- a/dictionary/dictionary_test.go +++ b/dictionary/dictionary_test.go @@ -70,3 +70,24 @@ func TestAdd(t *testing.T) { assertDefinition(t, dict, word, def) }) } + +func TestUpdate(t *testing.T) { + t.Run("update an existing word", func(t *testing.T) { + word := "test" + def := "this is just a test" + updated := "updated definition" + dict := Dictionary{word: def} + + dict.Update(word, updated) + assertDefinition(t, dict, word, updated) + }) + + t.Run("update an non-existing word", func(t *testing.T) { + word := "test" + updated := "updated definition" + dict := Dictionary{} + + err := dict.Update(word, updated) + assertError(t, err, ErrWordDoesNotExist) + }) +}