Skip to content

Instantly share code, notes, and snippets.

Created November 20, 2019 10:23
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shen-tian/3b6ff888e604abb4bf5bdead07062744 to your computer and use it in GitHub Desktop.
Firebase Push ID, in Clojurescript
(def firebase-push-id!
(let [last-push-time (atom nil)
saved-random (atom nil)]
(fn firebase-push-id-inner
([] (firebase-push-id-inner nil))
(locking last-push-time
(let [push-chars "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
now (or millis (.getTime (js/Date.)))
duplicate? (= now @last-push-time)
time-stamp (->> (range 7)
(reductions #(Math/floor (/ % 64)) now)
(map #(mod % 64))
inc-vec (fn [v pos]
(let [roll-over? (and (= (get v pos) 63)
(pos? pos))
bumped (update v pos #(mod (inc %) 64))]
(if-not roll-over?
(let [blah bumped]
(recur blah (dec pos))))))
last-random (let [new-random (if-not duplicate?
(mapv #(Math/floor (* (Math/random) 64))
(range 12))
(inc-vec @saved-random 12))]
(reset! saved-random new-random)
(reset! last-push-time now)
(->> (concat time-stamp last-random)
(map #(.charAt push-chars %))
(str/join ""))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment