Firebase Push ID, in Clojurescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def firebase-push-id! | |
(let [last-push-time (atom nil) | |
saved-random (atom nil)] | |
(fn firebase-push-id-inner | |
([] (firebase-push-id-inner nil)) | |
([millis] | |
(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)) | |
reverse) | |
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? | |
bumped | |
(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) | |
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