-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsearchwithkey.go
64 lines (55 loc) · 1.75 KB
/
searchwithkey.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
package hermes
import (
"errors"
"strings"
)
// SearchWithKey searches for all records containing the given query in the specified key column with a limit of results to return.
// Parameters:
// - c (c *Cache): A pointer to the Cache struct
// - sp (SearchParams): A SearchParams struct containing the search parameters.
//
// Returns:
// - []map[string]any: A slice of maps containing the search results
// - error: An error if the key, query or limit is invalid
func (c *Cache) SearchWithKey(sp SearchParams) ([]map[string]any, error) {
switch {
case len(sp.Key) == 0:
return []map[string]any{}, errors.New("invalid key")
case len(sp.Query) == 0:
return []map[string]any{}, errors.New("invalid query")
}
// Set the query to lowercase
sp.Query = strings.ToLower(sp.Query)
// Lock the mutex
c.mutex.RLock()
defer c.mutex.RUnlock()
// Search the data
return c.searchWithKey(sp), nil
}
// searchWithKey searches for all records containing the given query in the specified key column with a limit of results to return.
// Parameters:
// - c (c *Cache): A pointer to the Cache struct
// - sp (SearchParams): A SearchParams struct containing the search parameters.
//
// Returns:
// - []map[string]any: A slice of maps containing the search results
func (c *Cache) searchWithKey(sp SearchParams) []map[string]any {
// Define variables
var result []map[string]any = []map[string]any{}
// Iterate over the query result
for _, item := range c.data {
for _, v := range item {
if len(result) >= sp.Limit {
return result
}
// Check if the value contains the query
if v, ok := v.(string); ok {
if strings.Contains(strings.ToLower(v), sp.Query) {
result = append(result, item)
}
}
}
}
// Return the result
return result
}