forked from tmdvs/Go-Emoji-Utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emoji.go
108 lines (90 loc) · 2.22 KB
/
emoji.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
// Package emoji - package emoji
package emoji
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"github.com/biter777/Go-Emoji-Utils/utils"
)
// Emoji - Struct representing Emoji
type Emoji struct {
Key string `json:"key"`
Value string `json:"value"`
Descriptor string `json:"descriptor"`
}
// LoadFromFile - Load the Emoji definition JSON file and Unmarshal into map
// As example of filepath: "/path/data/emoji.json"
func LoadFromFile(filepath string) error {
// Open the Emoji definition JSON and Unmarshal into map
jsonFile, err := os.Open(filepath)
if jsonFile != nil {
defer jsonFile.Close()
}
if err != nil {
return err
}
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
return err
}
EmojisTmp := make(map[string]Emoji) // new map
err = json.Unmarshal(byteValue, &EmojisTmp)
if err != nil {
return err
}
Emojis = EmojisTmp
return nil
}
// LookupEmoji - Lookup a single emoji definition
func LookupEmoji(emojiString string) (emoji Emoji, err error) {
hexKey := utils.StringToHexKey(emojiString)
// If we have a definition for this string we'll return it,
// else we'll return an error
if e, ok := Emojis[hexKey]; ok {
emoji = e
} else {
err = fmt.Errorf("No record for \"%s\" could be found", emojiString)
}
return emoji, err
}
// LookupEmojis - Lookup definitions for each emoji in the input
func LookupEmojis(emoji []string) (matches []interface{}) {
for _, emoji := range emoji {
if match, err := LookupEmoji(emoji); err == nil {
matches = append(matches, match)
} else {
matches = append(matches, err)
}
}
return
}
// RemoveAll - Remove all emoji
func RemoveAll(input string) string {
// Find all the emojis in this string
matches := FindAll(input)
for _, item := range matches {
emo := item.Match.(Emoji)
rs := []rune(emo.Value)
for _, r := range rs {
input = strings.ReplaceAll(input, string([]rune{r}), "")
}
}
// Remove and trim and left over whitespace
return strings.TrimSpace(strings.Join(strings.Fields(input), " "))
//return input
}
// Random - random Emoji
func Random() Emoji {
rnd := rand.Intn(len(Emojis))
var count int
for _, e := range Emojis {
if rnd == count {
return e
}
count++
}
return Emoji{}
}