Skip to content

Instantly share code, notes, and snippets.

@joelittlejohn
Last active December 26, 2015 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelittlejohn/7217581 to your computer and use it in GitHub Desktop.
Save joelittlejohn/7217581 to your computer and use it in GitHub Desktop.
Create base62 ids with 64-bit entropy in Clojure
(let [digits (into [] (map char (concat (range 48 58) (range 65 91) (range 97 123)))) ;; 0-9,A-Z,a-z
base (biginteger (count digits))
entropy 64]
(defn id []
(loop [id10 (BigInteger. entropy (java.security.SecureRandom.))
id62 ""]
(if (and (<= id10 (BigInteger/ZERO)) (seq id62))
id62
(let [[d r] (.divideAndRemainder id10 base)]
(recur d (str id62 (digits (.intValue r)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment