Skip to content

Instantly share code, notes, and snippets.

@theikkila
Last active February 9, 2018 15:58
Show Gist options
  • Save theikkila/1bfd2ad5875e8c8dd1ae771dc9ec5cfe to your computer and use it in GitHub Desktop.
Save theikkila/1bfd2ad5875e8c8dd1ae771dc9ec5cfe to your computer and use it in GitHub Desktop.
Collection of clojure utilities and macros
(defmacro first-do
"Executes first expression of do-block and returns it's result after the rest of the body"
[fexpr & body]
`(let [a# ~fexpr]
(do ~@body a#)))
; EXAMPLE:
;(first-do
; (calculate-something 1 2 3)
; (send-metrics "finished-calculation-of-something" 2))
(defmacro let-go
"Like ordinary go-block but first param is symbol for channel thats returned automatically.
same as:
(let-go c
...something with c)
->
(let [c (chan)]
(go ...something with c)
c)"
[channel & body]
`(let [~channel (chan)]
(go ~@body)
~channel))
(defn ->uuid
"Convert UUID-formatted string to java UUID-object"
[s]
(java.util.UUID/fromString s))
; EXAMPLE:
; (->uuid "123e4567-e89b-12d3-a456-426655440000")
; #"123e4567-e89b-12d3-a456-426655440000"
(defn try-catch
"Evalute f in a try catch returning a vector with first element as possible exception and second element as evaluation result or default value. Default value defaults to nil"
([f] (try-catch f nil))
([f default]
(try [nil (f)]
(catch Exception e [e default]))))
(defmacro m-try-catch [body]
`(try-catch (fn [] (~@body))))
(defmacro m-try-catch-ignore [body]
`(second (try-catch (fn [] (~@body)))))
(def ^:private hex-chars
(byte-array (.getBytes "0123456789abcdef" "UTF-8")))
(defn bytes->hex
"Convert Byte Array to Hex String"
^String
[^"[B" data]
(let [len (alength data)
^"[B" buffer (byte-array (* 2 len))]
(loop [i 0]
(when (< i len)
(let [b (aget data i)]
(aset buffer (* 2 i) (aget hex-chars (bit-shift-right (bit-and b 0xF0) 4)))
(aset buffer (inc (* 2 i)) (aget hex-chars (bit-and b 0x0F))))
(recur (inc i))))
(String. buffer "UTF-8")))
(defn mapmap-kv [f m]
"maps hashmaps with pairs"
(reduce-kv (fn [prev k v]
(let [[n-k n-v] (f k v)]
(assoc prev n-k n-v))) {} m))
(defn mapmap [f m]
"maps hashmaps"
(mapmap-kv (fn [k v] (list k (f v))) m))
(defn now []
(System/currentTimeMillis))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment