-
Notifications
You must be signed in to change notification settings - Fork 0
/
emojis.go
124 lines (100 loc) · 1.97 KB
/
emojis.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package emoji
import (
"encoding/json"
"strings"
"sync"
)
type Emoji struct {
Emoji string `json:"emoji"`
SkinTones bool `json:"skin_tones"`
Aliases []string `json:"aliases"`
}
type EmojiTrieNode struct {
Emoji *Emoji
Children map[rune]*EmojiTrieNode
}
var (
emojis []*Emoji
emojisOnce sync.Once
emojisTrie *EmojiTrieNode
emojisTrieOnce sync.Once
)
func Emojis() []*Emoji {
emojisOnce.Do(func() {
err := json.Unmarshal(emojisJSON, &emojis)
if err != nil {
panic("failed to parse emojis JSON: " + err.Error())
}
})
return emojis
}
func addEmojiToTrie(emoji *Emoji) {
current := emojisTrie
for _, r := range emoji.Emoji {
child, ok := current.Children[r]
if !ok {
child = &EmojiTrieNode{
Children: map[rune]*EmojiTrieNode{},
}
current.Children[r] = child
}
current = child
}
current.Emoji = emoji
}
func EmojisTrie() *EmojiTrieNode {
emojisTrieOnce.Do(func() {
emojisTrie = &EmojiTrieNode{
Children: map[rune]*EmojiTrieNode{},
}
for _, emoji := range Emojis() {
addEmojiToTrie(emoji)
}
})
return emojisTrie
}
func EmojisToAliases(s string) string {
emojisTrie := EmojisTrie()
needsFixing := false
for _, r := range s {
if _, ok := emojisTrie.Children[r]; ok {
needsFixing = true
}
}
if !needsFixing {
return s
}
runes := []rune(s)
runesLen := len(runes)
var b strings.Builder
for i := 0; i < runesLen; i++ {
r := runes[i]
if _, ok := emojisTrie.Children[r]; ok {
var lastEmoji *Emoji
var lastEmojiJ int
node := emojisTrie
for j := 0; i+j < runesLen; j++ {
r := runes[i+j]
child, ok := node.Children[r]
if !ok {
break
}
if child.Emoji != nil {
lastEmoji = child.Emoji
lastEmojiJ = j
}
node = child
}
if lastEmoji != nil &&
len(lastEmoji.Aliases) > 0 {
b.WriteRune(':')
b.WriteString(lastEmoji.Aliases[0])
b.WriteRune(':')
i += lastEmojiJ
continue
}
}
b.WriteRune(r)
}
return b.String()
}