go-by-test/dictionary/dictionary.go

55 lines
1.0 KiB
Go
Raw Normal View History

2024-09-11 13:48:59 +02:00
package dictionary
2024-09-11 15:22:42 +02:00
type Dictionary map[string]string
2024-09-17 10:19:25 +02:00
const (
2024-09-17 11:31:00 +02:00
ErrNotFound = DictionaryErr("could not find the word you were looking for")
ErrWordExists = DictionaryErr("word exists")
ErrWordDoesNotExist = DictionaryErr("word does not exist")
2024-09-17 10:19:25 +02:00
)
type DictionaryErr string
// implements the Error interface, makes it an "error"
func (e DictionaryErr) Error() string {
return string(e)
}
2024-09-17 09:55:36 +02:00
func (d Dictionary) Search(word string) (string, error) {
2024-09-11 15:22:42 +02:00
result, ok := d[word]
2024-09-11 13:48:59 +02:00
if !ok {
2024-09-17 09:55:36 +02:00
return "", ErrNotFound
2024-09-11 13:48:59 +02:00
}
2024-09-17 09:55:36 +02:00
return result, nil
2024-09-11 13:48:59 +02:00
}
2024-09-17 10:10:07 +02:00
2024-09-17 10:19:25 +02:00
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
2024-09-17 10:10:07 +02:00
}
2024-09-17 11:31:00 +02:00
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
}
2024-09-17 11:35:22 +02:00
func (d Dictionary) Delete(word string) {
delete(d, word)
}