Skip to content

Instantly share code, notes, and snippets.

@mikelikesbikes
Created April 4, 2012 04:21
Show Gist options
  • Save mikelikesbikes/2297685 to your computer and use it in GitHub Desktop.
Save mikelikesbikes/2297685 to your computer and use it in GitHub Desktop.
Base62 encoding
(def alphabet "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
(defn encode [i, alphabet]
(reduce #(str (nth alphabet (last %2)) %) ""
(take-while
#(not= [0 0] %)
(rest
; this is the magic (creates a lazy sequence of tuples, consisting of quot and mod)
(iterate
(fn [[i _]]
(let [x (count alphabet)]
[(quot i x) (mod i x)]))
[i 0])))))
(defn decode [s, alphabet]
(reduce
(fn [val c]
(+ (* (count alphabet) val) (.indexOf alphabet (str c))))
0
s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment