diff options
| author | mo khan <mo.khan@gmail.com> | 2019-11-16 13:55:48 -0700 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2019-11-16 13:55:48 -0700 |
| commit | ec6f34b6e26def1516d03a94e4758eab4369a86c (patch) | |
| tree | 2916cb3ad7e11aee71a656d3fb9a1373333fa3ae | |
| parent | fadc9064e56cafcbda1597e2473b66c5a105b081 (diff) | |
play with maps
| -rw-r--r-- | dictionary.go | 22 | ||||
| -rw-r--r-- | dictionary_test.go | 46 |
2 files changed, 68 insertions, 0 deletions
diff --git a/dictionary.go b/dictionary.go new file mode 100644 index 0000000..a5d81b5 --- /dev/null +++ b/dictionary.go @@ -0,0 +1,22 @@ +package main + +import ( + "errors" +) + +type Dictionary map[string]string + +var ErrorNotFound = errors.New("could not find the word you were looking for") + +func (d Dictionary) Search(word string) (string, error) { + definition, ok := d[word] + if !ok { + return "", ErrorNotFound + } + + return definition, nil +} + +func (d Dictionary) Add(word, definition string) { + d[word] = definition +} diff --git a/dictionary_test.go b/dictionary_test.go new file mode 100644 index 0000000..89cd37b --- /dev/null +++ b/dictionary_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "testing" +) + +// https://github.com/quii/learn-go-with-tests/blob/master/maps.md +func TestSearch(t *testing.T) { + dictionary := Dictionary{"test": "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) + }) + + t.Run("unknown word", func(t *testing.T) { + _, got := dictionary.Search("unknown") + + assertError(t, got, ErrorNotFound) + }) +} + +func TestAdd(t *testing.T) { + dictionary := Dictionary{} + dictionary.Add("test", "this is just a test") + + want := "this is just a test" + got, err := dictionary.Search("test") + if err != nil { + t.Fatal("should find added word:", err) + } + + if want != got { + t.Errorf("got %q want %q", got, want) + } +} + +func assertStrings(t *testing.T, got, want string) { + t.Helper() + + if got != want { + t.Errorf("got %q want %q", got, want) + } +} |
