summaryrefslogtreecommitdiff
path: root/dictionary.go
blob: dd443aa35baa2b318e81c6183015d8ea5947a477 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

type Dictionary map[string]string
type DictionaryError string

var (
	ErrorNotFound         = DictionaryError("could not find the word you were looking for")
	ErrorWordDoesNotExist = DictionaryError("cannot update word because it does not exist")
	ErrorWordExists       = DictionaryError("cannot add word because it already exists")
)

func (e DictionaryError) Error() string {
	return string(e)
}

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) error {
	_, err := d.Search(word)

	switch err {
	case ErrorNotFound:
		d[word] = definition
		return nil
	case nil:
		return ErrorWordExists
	default:
		return err
	}
}

func (d Dictionary) Update(word, definition string) error {
	_, err := d.Search(word)

	switch err {
	case ErrorNotFound:
		return ErrorWordDoesNotExist
	case nil:
		d[word] = definition
		return nil
	default:
		return err
	}
}

func (d Dictionary) Delete(word string) {
	delete(d, word)
}