-
-
Save sanbiv/136b92115a62eb3a71b2315b9b037f39 to your computer and use it in GitHub Desktop.
Encoding/decoding functions for a URL Shortner -- in Ruby
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
module UrlShortener | |
class << self | |
CODESET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
BASE = CODESET.length # 62 | |
def encode(id) | |
hash = '' | |
while id > 0 | |
hash = CODESET[id % BASE].chr + hash | |
id = (id.to_f / BASE.to_f).floor | |
end | |
hash | |
end | |
def decode(hash) | |
id = 0 | |
hash.chars.each_with_index do |c,i| | |
n = CODESET.index(c) | |
return if n < 0 # invalid codeset | |
id += n * (BASE ** (hash.length-i-1)) | |
end | |
id | |
end | |
end | |
end | |
__END__ | |
Usage: | |
Normally a web resource is referenced by a unique integer as in: http://site.com/posts/300. | |
The methods above simply encode the integer to base 62 with the codeset defined above. | |
It's the same thing as converting base 10 to base 16 (hex), but in this case we're converting | |
base 10 to our own base 62. | |
UrlShortener.encode(300) | |
=> "4Q" | |
UrlShortener.decode("4Q") | |
=> 300 | |
UrlShortener.encode(1000000) | |
=> "4c92" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment