all repos — emoji @ 6e3e6aef7ad024165bb9dddb49e79d49b1689a5e

A minimalistic emoji package for Go (golang)

emoji.go (view raw)

 1package emoji
 2
 3import (
 4	"fmt"
 5	"html"
 6	"strings"
 7)
 8
 9const (
10	Default     Tone = ""
11	Light       Tone = "\U0001F3FB"
12	MediumLight Tone = "\U0001F3FC"
13	Medium      Tone = "\U0001F3FD"
14	MediumDark  Tone = "\U0001F3FE"
15	Dark        Tone = "\U0001F3FF"
16
17	unicodeFlagBaseIndex = 127397
18)
19
20type Emoji string
21
22func (e Emoji) String() string {
23	return string(e)
24}
25
26type EmojiWithTone Emoji
27
28func (e EmojiWithTone) String() string {
29	return strings.ReplaceAll(string(e), "@", string(Default))
30}
31
32func (e EmojiWithTone) Tone(tones ...Tone) EmojiWithTone {
33	str := string(e)
34	for _, tone := range tones {
35		str = strings.Replace(str, "@", string(tone), 1)
36	}
37
38	if strings.Count(str, "@") > 0 {
39		lastTone := tones[len(tones)-1]
40		str = strings.ReplaceAll(str, "@", string(lastTone))
41	}
42
43	return EmojiWithTone(str)
44}
45
46type Tone string
47
48func (t Tone) String() string {
49	return string(t)
50}
51
52func CountryFlag(code string) (Emoji, error) {
53	if len(code) != 2 {
54		return "", fmt.Errorf("not valid country code: %q", code)
55	}
56
57	code = strings.ToUpper(code)
58	flag := countryCodeLetter(code[0]) + countryCodeLetter(code[1])
59
60	return Emoji(flag), nil
61}
62
63func countryCodeLetter(l byte) string {
64	return html.UnescapeString(fmt.Sprintf("&#%v;", unicodeFlagBaseIndex+int(l)))
65}