Skip to content

Instantly share code, notes, and snippets.

@tmountain
Created January 29, 2010 17:00
Show Gist options
  • Save tmountain/289890 to your computer and use it in GitHub Desktop.
Save tmountain/289890 to your computer and use it in GitHub Desktop.
(ns id-gen)
(def ids "abcdefghijklmnopqrstuvwxyz")
(defn create-generator []
"returns a generator ref"
(ref {:ids ids, :pos 0}))
(defn- inc-gen
"increments generator counter
must be called from within a transaction"
[gen]
(alter gen assoc :pos (inc (:pos @gen))))
(defn- get-chars
"gets the next char(s) in the sequence"
[s offset]
(if (>= offset (count s))
(let [div-val (dec (int (/ offset (count s))))
mod-val (mod offset (count s))]
(apply str (get-chars s div-val) (get-chars s mod-val)))
(subs s offset (inc offset))))
(defn get-id [gen]
(dosync
(let [pos (:pos @gen)]
(inc-gen gen)
(get-chars (:ids @gen) pos))))
(def g (create-generator))
(println (pr-str (for [x (range 777)] (get-id g))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment