dict: deal with unknown keys
This commit is contained in:
		@ -1,11 +1,15 @@
 | 
				
			|||||||
package dictionary
 | 
					package dictionary
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import "errors"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
type Dictionary map[string]string
 | 
					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]
 | 
						result, ok := d[word]
 | 
				
			||||||
	if !ok {
 | 
						if !ok {
 | 
				
			||||||
		return ""
 | 
							return "", ErrNotFound
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	return result
 | 
						return result, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
				
			|||||||
@ -13,8 +13,20 @@ func assertStrings(t testing.TB, got, want string) {
 | 
				
			|||||||
func TestSearch(t *testing.T) {
 | 
					func TestSearch(t *testing.T) {
 | 
				
			||||||
	dictionary := Dictionary{"test": "this is just a test"}
 | 
						dictionary := Dictionary{"test": "this is just a test"}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	got := dictionary.Search("test")
 | 
						t.Run("known word", func(t *testing.T) {
 | 
				
			||||||
 | 
							got, _ := dictionary.Search("test")
 | 
				
			||||||
		want := "this is just a 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)
 | 
				
			||||||
 | 
						})
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user