-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
core.clj
116 lines (97 loc) · 2.9 KB
/
core.clj
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
(ns emoji.core
"Core functions"
(:require [clojure.java.io :as io]
[clojure.data.json :as json]
[clojure.string :as string]))
(def emojis
"Keywordized emoji data from the `resources/emojis.json`"
(with-open [r (io/reader (io/resource "emojis.json"))]
(-> (json/read r :key-fn keyword))))
(def ^:private alias-map
"Map from `:alias` to emoji."
(into {}
(mapcat (fn [{:keys [aliases] :as emoji}]
(map (fn [alias] [(keyword alias) emoji])
aliases)))
emojis))
(defn ->emoji
"Convert a `alias` string to emoji unicode.
```clojure
(->emoji \"thumbsup\")
;; => \"👍\"
```"
[alias]
(-> alias keyword alias-map :emoji))
;;
;; Emojify
;;
(defn emojify
"Replace emoji aliases in a string with unicode codes.
```clojure
(emojify \"Clojure is awesome :thumbsup:\")
;; => \"Clojure is awesome 👍\"
```"
[s]
(string/replace s
#"(:)([-+\w]+)(:)"
(fn [[_ delimeter_1 alias delimeter_2]] (-> alias ->emoji))))
(defn emojify-all
"Replace every word in a sentence to emoji if it is an alias.
Be aware. This function might make you very annoying.
```clojure
(emojify-all \"Clojure pizza fire thumbsup smile\")
;; => \"Clojure 🍕 🔥 👍 😄\"
```"
[s]
(->> (string/split s #" ")
(map #(or (->emoji %) %))
(string/join " ")))
;;
;; Demojify
;;
(def ^:private regex-char-esc-smap
;; Stole frome https://stackoverflow.com/a/11672480
(let [esc-chars "()*&^%$#!"]
(zipmap esc-chars
(map #(str "\\" %) esc-chars))))
(defn- escape-regex-char
;; Stole frome https://stackoverflow.com/a/11672480
[string]
(->> string
(replace regex-char-esc-smap)
(apply str)))
(def ^:private emoji-unicode-pattern
(let [emojis-by-length (->> emojis
(map :emojiChar)
(sort-by count #(compare %2 %1)))
regex-str (->> emojis-by-length
(map escape-regex-char)
(string/join "|"))]
(re-pattern (str "(" regex-str ")"))))
(def ^:private unicode-map
"Map from `:emojiChar` keyword to emoji."
(into {}
(map (fn [{:keys [emojiChar] :as emoji}] [(keyword emojiChar) emoji]))
emojis))
(defn ->alias
"Convert a `unicode` string to emoji shortcode/alias.
```clojure
(->alias \"👍\")
;; => \"thumbsup\"
```"
[unicode]
(let [emoji (-> unicode keyword unicode-map)]
(str ":" (last (:aliases emoji)) ":")))
(defn demojify
"Replace emoji unicodes in a string with shortcodes/aliases.
```clojure
(emojify \"Clojure is awesome 👍\")
;; => \"Clojure is awesome :thumbsup:\"
```"
[s]
(string/replace s
emoji-unicode-pattern
(fn [[_ unicode]] (->alias unicode))))
(comment
(def pattern #"(:)([-+\w]+)(:)")
(re-find pattern "Clojure :thumbsup:"))