Skip to content

Instantly share code, notes, and snippets.

@Rafe
Created August 2, 2012 03:12
Show Gist options
  • Save Rafe/3232892 to your computer and use it in GitHub Desktop.
Save Rafe/3232892 to your computer and use it in GitHub Desktop.
url hash
getAlgorithms = -> ['md5', 'sha1', 'sha256', 'sha512']
generateCode = (url, algorithms, digits, callback)->
#increase code digits if all codes are registered
if algorithms.length is 0
algorithms = getAlgorithms()
digits += 1
algorithm = algorithms.shift()
code = hashUrl(url, digits, algorithm)
redis.get "url:#{code}", (err, reply)->
if not reply or reply == url
redis.set "url:#{code}", url, (err, reply)->
callback(null, code)
else generateCode(url, algorithms, digits, callback)
exports.hashUrl = hashUrl = (url, digits = 5, algorithm = 'md5')->
symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
length = symbols.length
code = ""
hash = crypto.createHash(algorithm)
.update(url)
.digest('hex')
hash_number = parseInt(hash, 16) % Math.pow(length, digits + 1)
while hash_number >= length
n = hash_number % length
code += symbols[n]
hash_number = parseInt(hash_number / length)
code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment