url shortener using base 62

Trying to scratch an itch one weekend, I tried to write my own URL shortener service. After all, bit.ly got $2M funding for offering such service so I went ahead and see how hard it is to create one. If you've been doing web development for sometime, this activity is trivial. The only hurdle I have was how to generate those random looking string appended at the end of the domain url. For the lazy there's always Base36 that look like the one tinyurl is using. I wanted mine to resemble is.gd so I wrote my own. Here's one I quickly wrote in ruby.

CODE:
  1. class B62
  2.   CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split('')
  3.   BASE = 62
  4.   def self.encode(value)
  5.     s = []
  6.     while value > BASE
  7.       value, rem = value.divmod(BASE)
  8.       s << CHARS[rem]
  9.     end
  10.     s << CHARS[value]
  11.     s.reverse.to_s
  12.   end
  13.    
  14.   def self.decode(str)
  15.     str = str.split('').reverse
  16.     total = 0
  17.     str.each_with_index do |v,k|
  18.       total += (CHARS.index(v) * (BASE ** k))
  19.     end
  20.     total
  21.   end
  22. end

Hope that helps.

Leave a Reply