From ec6f34b6e26def1516d03a94e4758eab4369a86c Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 16 Nov 2019 13:55:48 -0700 Subject: play with maps --- dictionary.go | 22 ++++++++++++++++++++++ dictionary_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 dictionary.go create mode 100644 dictionary_test.go 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) + } +} -- cgit v1.2.3