parser.go (view raw)
1package emoji
2
3import (
4 "fmt"
5 "strings"
6 "unicode"
7)
8
9// Parse replaces emoji aliases (:pizza:) with unicode representation.
10func Parse(input string) string {
11 var matched strings.Builder
12 var output strings.Builder
13
14 for _, r := range input {
15 // when it's not `:`, it might be inner or outer of the emoji alias
16 if r != ':' {
17 // if matched is empty, it's the outer of the emoji alias
18 if matched.Len() == 0 {
19 output.WriteRune(r)
20 continue
21 }
22
23 matched.WriteRune(r)
24
25 // if it's space, the alias's not valid.
26 // reset matched for breaking the emoji alias
27 if unicode.IsSpace(r) {
28 output.WriteString(matched.String())
29 matched.Reset()
30 }
31 continue
32 }
33
34 // r is `:` now
35 // if matched is empty, it's the beginning of the emoji alias
36 if matched.Len() == 0 {
37 matched.WriteRune(r)
38 continue
39 }
40
41 // it's the end of the emoji alias
42 alias := matched.String() + ":"
43
44 code, ok := emojiMap[alias]
45 if ok {
46 output.WriteString(code)
47 matched.Reset()
48 } else {
49 // TODO: check for country codes: `flag-[a-z]{2}`
50 output.WriteString(matched.String())
51 // it might be the beginning of the another emoji alias
52 matched.Reset()
53 matched.WriteRune(r)
54 }
55 }
56
57 // if matched not empty, add it to output
58 if matched.Len() != 0 {
59 output.WriteString(matched.String())
60 matched.Reset()
61 }
62
63 return output.String()
64}
65
66// Map returns the emojis map.
67// Key is the alias of the emoji.
68// Value is the code of the emoji.
69func Map() map[string]string {
70 return emojiMap
71}
72
73// AppendAlias adds new emoji pair to the emojis map.
74func AppendAlias(alias, code string) error {
75 if c, ok := emojiMap[alias]; ok {
76 return fmt.Errorf("emoji already exist: %q => %+q", alias, c)
77 }
78
79 for _, r := range alias {
80 if unicode.IsSpace(r) {
81 return fmt.Errorf("emoji alias is not valid: %q", alias)
82 }
83 }
84
85 emojiMap[alias] = code
86
87 return nil
88}
89
90// Exist checks existence of the emoji by alias.
91func Exist(alias string) bool {
92 _, ok := emojiMap[alias]
93
94 return ok
95}
96
97// Find returns the emoji code by alias.
98func Find(alias string) (string, bool) {
99 code, ok := emojiMap[alias]
100 if !ok {
101 return "", false
102 }
103
104 return code, true
105}