Commit ec6f34b

mo khan <mo.khan@gmail.com>
2019-11-16 20:55:48
play with maps
1 parent fadc906
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
+}
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)
+	}
+}