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:
-
class B62
-
CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split('')
-
BASE = 62
-
def self.encode(value)
-
s = []
-
while value > BASE
-
value, rem = value.divmod(BASE)
-
s << CHARS[rem]
-
end
-
s << CHARS[value]
-
s.reverse.to_s
-
end
-
-
def self.decode(str)
-
str = str.split('').reverse
-
total = 0
-
str.each_with_index do |v,k|
-
total += (CHARS.index(v) * (BASE ** k))
-
end
-
total
-
end
-
end
Hope that helps.