(def sid-batch 10) (def sid-pool (atom {:cnt 0 :sids '()})) (defn get-sid [] (first (:sids (swap! sid-pool (fn [{:keys [cnt sids]}] (if-let [sids (next sids)] {:cnt cnt :sids sids} {:sids (range cnt (+ sid-batch cnt)) :cnt (+ cnt sid-batch)}))))))
As I said in my comment, I think you have the right idea: "abuse the field in sid-pool". Besides the fact that you do not need a field, just call (comp first sids) on the return value from swap!
I removed inc in the range call because it caused the generator to skip a multiple of 10.
And return the sid to the pool:
(defn return-sid [sid] (swap! sid-pool (fn [{:keys [cnt [_ & ids]]}] {:cnt cnt :sids (list* _ sid ids)})))
source share