UP | HOME

Clojure helpers

Table of Contents

These are helpful functions I include in all my Clojure(Script) projects.

Note not all of them are my own original idea.

1 Clojure

1.1 logging

Just call log with any number of strings as arguments.

(defn log
  "concatenate and save to file"
  [& strings]
  (spit "/tmp/cljdebug.txt" (str (reduce str strings) "
")))  

1.2 map-of

For when you need to put some variables into map format:

(defmacro map-of
  [& xs]
  `(hash-map ~@(mapcat (juxt keyword identity) xs)))

1.3 url encoding

Shortcut for URL encoding/decoding

(defn urlencode [foo]
  (java.net.URLEncoder/encode foo "UTF-8"))

(defn urldecode [foo]
  (java.net.URLDecoder/decode foo "UTF-8"))

2 ClojureScript

2.1 logging

Just call log with any number of strings as arguments.

(defn log
  "concatenate and print to console"
  [& strings]
  ((.-log js/console) (reduce str strings)))

2.2 get by id/class

Simple shortcuts

(defn byid
  "shortcut for getting element by id"
  [id]
  (.getElementById js/document id))

(defn byclass
  "shortcut for getting element by class"
  [name]
  (.getElementsByClassName js/document name))

2.3 allow NodeList & HTMLCollection to be treated as collection

To avoid having to use (.from js/Array foo) all the time. Just put these somewhere and you can access NodeList & HTMLCollection just like any other collection:

(extend-type js/NodeList
  ISeqable
  (-seq [array] (array-seq array 0)))

(extend-type js/HTMLCollection
  ISeqable
  (-seq [array] (array-seq array 0)))

Copyright 2023 Joseph Graham (joseph@xylon.me.uk)