dict: deal with unknown keys

This commit is contained in:
vinchent 2024-09-17 09:55:36 +02:00
parent baff9ee722
commit fc67cf14ff
2 changed files with 23 additions and 7 deletions

View File

@ -1,11 +1,15 @@
package dictionary
import "errors"
type Dictionary map[string]string
func (d Dictionary) Search(word string) string {
var ErrNotFound = errors.New("could not find the word you were looking for")
func (d Dictionary) Search(word string) (string, error) {
result, ok := d[word]
if !ok {
return ""
return "", ErrNotFound
}
return result
return result, nil
}

View File

@ -3,7 +3,7 @@ package dictionary
import "testing"
func assertStrings(t testing.TB, got, want string) {
t.Helper()
t.Helper()
if got != want {
t.Errorf("got %q want %q given %q", got, want, "test")
@ -13,8 +13,20 @@ func assertStrings(t testing.TB, got, want string) {
func TestSearch(t *testing.T) {
dictionary := Dictionary{"test": "this is just a test"}
got := dictionary.Search("test")
want := "this is just a test"
t.Run("known word", func(t *testing.T) {
got, _ := dictionary.Search("test")
want := "this is just a test"
assertStrings(t, got, want)
assertStrings(t, got, want)
})
t.Run("unknown word", func(t *testing.T) {
_, err := dictionary.Search("undefined")
want := "could not find the word you were looking for"
if err == nil {
t.Fatal("expected to get an error")
}
assertStrings(t, err.Error(), want)
})
}