emote: parse emote structs, not just ids

This commit is contained in:
Branden J Brown 2025-04-19 19:17:35 -04:00
parent 5c530a41fb
commit 76fc85b7c0
2 changed files with 15 additions and 15 deletions

View File

@ -23,23 +23,23 @@ type Emote struct {
// //
// Parser assumes that emotes are bound by whitespace. // Parser assumes that emotes are bound by whitespace.
type Parser struct { type Parser struct {
m map[string]string m map[string]Emote
// TODO(branden): more efficient data structure; trie? // TODO(branden): more efficient data structure; trie?
} }
// NewParser creates a Parser for the given list of emotes. // NewParser creates a Parser for the given list of emotes.
func NewParser(emotes ...Emote) Parser { func NewParser(emotes ...Emote) Parser {
m := make(map[string]string, len(emotes)) m := make(map[string]Emote, len(emotes))
for _, e := range emotes { for _, e := range emotes {
m[e.Name] = e.ID m[e.Name] = e
} }
return Parser{m} return Parser{m}
} }
// Next parses the next emote instance from the message and returns the // Next parses the next emote instance from the message and returns the
// remainder of the message text following it. // remainder of the message text following it.
// If there is no emote in the message the returned emote is the empty string. // If there is no emote in the message the returned emote has an empty ID.
func (p Parser) Next(text string) (name, id, following string) { func (p Parser) Next(text string) (emote Emote, following string) {
for text != "" { for text != "" {
// First trim any existing space. // First trim any existing space.
text = strings.TrimSpace(text) text = strings.TrimSpace(text)
@ -54,12 +54,12 @@ func (p Parser) Next(text string) (name, id, following string) {
} else { } else {
following = "" following = ""
} }
id = p.m[word] em := p.m[word]
if id != "" { if em.ID != "" {
return word, id, following return em, following
} }
text = following text = following
} }
// No emote found. // No emote found.
return "", "", "" return Emote{}, ""
} }

View File

@ -57,16 +57,16 @@ func TestParser(t *testing.T) {
var got []string var got []string
text := c.text text := c.text
for { for {
name, id, rest := p.Next(text) em, rest := p.Next(text)
if id == "" { if em.ID == "" {
break break
} }
if name != id { if em.Name != em.ID {
// Not normally the case, but this test is constructed // Not normally the case, but this test is constructed
// so that it is. // so that it is.
t.Errorf("wrong id %q for name %q", id, name) t.Errorf("wrong id %q for name %q", em.ID, em.Name)
} }
got = append(got, name) got = append(got, em.Name)
text = rest text = rest
} }
if diff := cmp.Diff(c.want, got); diff != "" { if diff := cmp.Diff(c.want, got); diff != "" {
@ -103,7 +103,7 @@ func BenchmarkParser(b *testing.B) {
for b.Loop() { for b.Loop() {
text := c.text text := c.text
for text != "" { for text != "" {
_, _, text = p.Next(text) _, text = p.Next(text)
} }
} }
}) })