Skip to content

Instantly share code, notes, and snippets.

@daocren
Created January 6, 2013 03:54
Show Gist options
  • Save daocren/4465102 to your computer and use it in GitHub Desktop.
Save daocren/4465102 to your computer and use it in GitHub Desktop.
短地址工具
/**
* @method hasher
* @param {String} URL URL to be hashed
* @returns {String} hash Base 62 hash representation of the URL
**/
var hasher = exports.hasher = function(URL, length) {
if (!length) length = 6;
var AUID = [],
CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
for (var i = 0; i < length; i++) {
AUID.push(CHARS[Math.floor(Math.random()*62)]);
}
return AUID.join('');
};
/**
* @method generate
* @param {String} URL URL to create a Short URL of
* @param {Functon} callback Callback to execute on completion
**/
var generate = exports.generate = function( options, callback) {
var timeStamp = require('os').uptime;
var hashedURL
, customData;
// options takes an optional object literal
// right now it only supports an options.length argument
if (arguments.length === 2 && arguments[1] instanceof Function) {
callback = arguments[1];
hashedURL = hasher(timeStamp);
} else if (arguments.length === 3 && arguments[1] instanceof Object && arguments[2] instanceof Function) {
hashedURL = (options.length) ? hasher(timeStamp, options.length) : hasher(timeStamp);
customData = (options.data) ? options.data : null;
} else {
throw new Error("generate requires a URL and callback function!");
};
callback(null, hashedURL);
};
generate({},function(error,o){
console.log(o);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment