-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
95 lines (74 loc) · 1.61 KB
/
index.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package gofindit
import (
"errors"
"math/rand/v2"
"sync"
)
type Index struct {
Documents map[string]*Document
Filters []FilterFunc
// Cache
Cache bool
CacheSize int
mu sync.RWMutex
}
type Options struct {
// Cache
Cache bool // Whether or not to cache search results
CacheSize int // The maximum number of search results to cache
// Filters
Filters []FilterFunc // The filters to apply to strings
}
func New() *Index {
index := Index{
Documents: make(map[string]*Document),
Filters: DefaultFilters,
Cache: true,
CacheSize: 100,
}
return &index
}
// NewOptions returns a new index with the given options
func NewOptions(options Options) *Index {
index := Index{
Documents: make(map[string]*Document),
Filters: options.Filters,
Cache: options.Cache,
CacheSize: options.CacheSize,
}
return &index
}
func (i *Index) Random() (string, any) {
// Get array of document keys
var keys []string
for k := range i.Documents {
keys = append(keys, k)
}
// Get random key
key := keys[rand.IntN(len(keys))]
return key, i.Documents[key].Original
}
func (i *Index) Index(id string, doc any) error {
i.mu.Lock()
defer i.mu.Unlock()
// Make sure id isnt taken
if _, ok := i.Documents[id]; ok {
return errors.New("id already taken")
}
docNew, err := NewDoc(doc)
if err != nil {
return err
}
i.Documents[id] = docNew
return nil
}
// Get returns the document with the given ID
func (i *Index) Get(id string) (any, error) {
i.mu.RLock()
defer i.mu.RUnlock()
doc, ok := i.Documents[id]
if !ok {
return nil, errors.New("document not found")
}
return doc.Original, nil
}