/ gomoji.go
gomoji.go
1 package gomoji 2 3 import ( 4 "bytes" 5 "errors" 6 "strings" 7 8 "github.com/rivo/uniseg" 9 ) 10 11 // errors 12 var ( 13 ErrStrNotEmoji = errors.New("the string is not emoji") 14 ) 15 16 // Emoji is an entity that represents comprehensive emoji info. 17 type Emoji struct { 18 Slug string `json:"slug"` 19 Character string `json:"character"` 20 UnicodeName string `json:"unicode_name"` 21 CodePoint string `json:"code_point"` 22 Group string `json:"group"` 23 SubGroup string `json:"sub_group"` 24 } 25 26 // ContainsEmoji checks whether given string contains emoji or not. It uses local emoji list as provider. 27 func ContainsEmoji(s string) bool { 28 gr := uniseg.NewGraphemes(s) 29 for gr.Next() { 30 if _, ok := emojiMap[gr.Str()]; ok { 31 return true 32 } 33 } 34 35 return false 36 } 37 38 // AllEmojis gets all emojis from provider. 39 func AllEmojis() []Emoji { 40 return emojiMapToSlice(emojiMap) 41 } 42 43 // RemoveEmojis removes all emojis from the s string and returns a new string. 44 func RemoveEmojis(s string) string { 45 cleanBuf := bytes.Buffer{} 46 47 gr := uniseg.NewGraphemes(s) 48 for gr.Next() { 49 if _, ok := emojiMap[gr.Str()]; !ok { 50 cleanBuf.Write(gr.Bytes()) 51 } 52 } 53 54 return strings.TrimSpace(cleanBuf.String()) 55 } 56 57 // GetInfo returns a gomoji.Emoji model representation of provided emoji. 58 // If the emoji was not found, it returns the gomoji.ErrStrNotEmoji error 59 func GetInfo(emoji string) (Emoji, error) { 60 em, ok := emojiMap[emoji] 61 if !ok { 62 return Emoji{}, ErrStrNotEmoji 63 } 64 65 return em, nil 66 } 67 68 // FindAll finds all emojis in given string. If there are no emojis it returns a nil-slice. 69 func FindAll(s string) []Emoji { 70 var emojis []Emoji 71 72 gr := uniseg.NewGraphemes(s) 73 for gr.Next() { 74 if em, ok := emojiMap[gr.Str()]; ok { 75 emojis = append(emojis, em) 76 } 77 } 78 79 return emojis 80 } 81 82 func emojiMapToSlice(em map[string]Emoji) []Emoji { 83 emojis := make([]Emoji, 0, len(em)) 84 for _, emoji := range em { 85 emojis = append(emojis, emoji) 86 } 87 88 return emojis 89 }