Skip to content

Instantly share code, notes, and snippets.

@martinklepsch
Last active April 23, 2022 20:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinklepsch/8730542 to your computer and use it in GitHub Desktop.
Save martinklepsch/8730542 to your computer and use it in GitHub Desktop.
Generate a random HEX color in cojure or clojurescript
(require '[clojure.string :as s])
;; My initial attempt
(def c [:0 :1 :2 :3 :4 :5 :6 :7 :8 :9 :A :B :C :D :E :F])
(str "#" (s/join (map name (repeatedly 6 #(rand-nth c)))))
;; Another option not using keywords (/ht locks in #clojure)
(def c [0 1 2 3 4 5 6 7 8 9 \A \B \C \D \E \F])
(str "#" (s/join (repeatedly 6 #(rand-nth c))))
;; the last line can be simplified even more (/ht xificurC in #clojure)
(apply str \# (repeatedly 6 #(rand-nth c)))
;; This works on Clojure (/ht wei__ in #clojure)
(format "%x" (rand-int 16rFFFFFF))
;; this works in Clojurescript
(.toString (rand-int 16rFFFFFF) 16)
@apeckham
Copy link

apeckham commented Jun 3, 2016

(str/upper-case (format "%06x" (rand-int 16rFFFFFF)))

^ added the zero padding, thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment