Created
August 2, 2012 03:12
-
-
Save Rafe/3232892 to your computer and use it in GitHub Desktop.
url hash
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
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) |
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
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