Created
April 4, 2012 04:21
-
-
Save mikelikesbikes/2297685 to your computer and use it in GitHub Desktop.
Base62 encoding
This file contains hidden or 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 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