Skip to content

Instantly share code, notes, and snippets.

@sanbiv
Forked from pkieltyka/url_shortener.rb
Created July 20, 2016 13:28
Show Gist options
  • Save sanbiv/136b92115a62eb3a71b2315b9b037f39 to your computer and use it in GitHub Desktop.
Save sanbiv/136b92115a62eb3a71b2315b9b037f39 to your computer and use it in GitHub Desktop.
Encoding/decoding functions for a URL Shortner -- in Ruby
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