forked from Minecraft/canopeas
53 lines
1.1 KiB
Go
53 lines
1.1 KiB
Go
package track
|
|
|
|
import "strings"
|
|
|
|
// Tracker is a mapping of tracked words to a set of user IDs
|
|
type Tracker map[string]map[string]struct{}
|
|
|
|
// New returns an initialized Tracker
|
|
func New() Tracker {
|
|
return make(Tracker)
|
|
}
|
|
|
|
// Add a user ID tracking a word
|
|
func (t Tracker) Add(word, userID string) {
|
|
if _, ok := t[word]; !ok {
|
|
t[word] = make(map[string]struct{})
|
|
}
|
|
t[word][userID] = struct{}{}
|
|
}
|
|
|
|
// Remove a user ID tracking a word
|
|
func (t Tracker) Remove(word, userID string) bool {
|
|
if _, ok := t[word][userID]; ok {
|
|
delete(t[word], userID)
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Search for a tracked word and return the list of unique user IDs
|
|
func (t Tracker) Search(msg string) []string {
|
|
tokens := make(map[string]struct{})
|
|
fields := strings.Fields(msg)
|
|
for _, field := range fields {
|
|
field = strings.Trim(field, `.,;:'"!?`)
|
|
tokens[field] = struct{}{}
|
|
}
|
|
|
|
set := make(map[string]struct{}, 0)
|
|
for word, users := range t {
|
|
if _, ok := tokens[word]; ok {
|
|
for user := range users {
|
|
set[user] = struct{}{}
|
|
}
|
|
}
|
|
}
|
|
users := make([]string, 0, len(set))
|
|
for user := range set {
|
|
users = append(users, user)
|
|
}
|
|
return users
|
|
}
|