go-by-test/dictionary/dictionary.go
2024-09-17 11:35:22 +02:00

55 lines
1.0 KiB
Go

package dictionary
type Dictionary map[string]string
const (
ErrNotFound = DictionaryErr("could not find the word you were looking for")
ErrWordExists = DictionaryErr("word exists")
ErrWordDoesNotExist = DictionaryErr("word does not exist")
)
type DictionaryErr string
// implements the Error interface, makes it an "error"
func (e DictionaryErr) Error() string {
return string(e)
}
func (d Dictionary) Search(word string) (string, error) {
result, ok := d[word]
if !ok {
return "", ErrNotFound
}
return result, nil
}
func (d Dictionary) Add(word, definition string) error {
_, err := d.Search(word)
switch err {
case ErrNotFound:
d[word] = definition
case nil:
return ErrWordExists
default:
return err
}
return nil
}
func (d Dictionary) Update(word, definition string) error {
_, err := d.Search(word)
switch err {
case ErrNotFound:
return ErrWordDoesNotExist
case nil:
d[word] = definition
default:
return err
}
return nil
}
func (d Dictionary) Delete(word string) {
delete(d, word)
}