Skip to content

Instantly share code, notes, and snippets.

@allex
Created August 10, 2014 04:35
Show Gist options
  • Save allex/9b821248c36787ba66c0 to your computer and use it in GitHub Desktop.
Save allex/9b821248c36787ba66c0 to your computer and use it in GitHub Desktop.
// Author: Allex Wang ([email protected])
// GistID: 9b821248c36787ba66c0
// GistURL: https://gist.github.com/9b821248c36787ba66c0
// refer to: http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
function bitwise(str) {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
var ch = str.charCodeAt(i);
hash = ((hash << 5) - hash) + ch;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
// convert 10 binary to customized binary, max is 62
function binaryTransfer(integer, binary) {
binary = binary || 62;
var stack = [];
var num;
var result = '';
var sign = integer < 0 ? '-' : '';
function table (num) {
var t = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return t[num];
}
integer = Math.abs(integer);
while (integer >= binary) {
num = integer % binary;
integer = Math.floor(integer / binary);
stack.push(table(num));
}
if (integer > 0) {
stack.push(table(integer));
}
for (var i = stack.length - 1; i >= 0; i--) {
result += stack[i];
}
return sign + result;
}
/**
* why choose 61 binary, because we need the last element char to replace the minus sign
* eg: -aGtzd will be ZaGtzd
*/
function unique (text) {
var id = binaryTransfer(bitwise(text), 61);
return id.replace('-', 'Z');
}
exports.bitwise = bitwise;
exports.binaryTransfer = binaryTransfer;
exports.unique = unique;
@grrenier
Copy link

Hi Allex, Nice Work!! I'm using your code but I need to generate a 5 chars Hash using 'abcdefghijklmnopqrstuvwxyz'. Have you any suggestion that can help me to accomplish that?. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment