Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Created June 2, 2015 02:10
Show Gist options
  • Save HakurouKen/b4b4340091a83b23225e to your computer and use it in GitHub Desktop.
Save HakurouKen/b4b4340091a83b23225e to your computer and use it in GitHub Desktop.
javascript string hash
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root['strHash'] = factory();
}
}(this, function () {
var strHash = {
SDBM: function(str){
var hash = 0,
i, l;
for( i = 0, l = str.length; i < l ; i++ ){
hash = str.charCodeAt(i) + (hash << 6) + (hash << 16) - hash;
}
return (hash & 0x7FFFFFFF).toString(16);
},
RS: function(str){
var b = 378551,
a = 63689,
hash = 0,
i, l;
for( i = 0, l = str.length; i < l; i++ ){
// hash = hash * a + str.charCodeAt(i);
hash = (hash & 0xFFFF) * (a & 0xFFFF) +
(((hash >> 16) * (a & 0xFFFF)) << 16) +
(((hash & 0xFFFF) * (a >> 16)) << 16) + str.charCodeAt(i);
hash &= 0xFFFFFFFF;
a = (a * b) & 0xFFFFFFFF;
}
return (hash & 0x7FFFFFFF).toString(16);
},
JS: function(str){
var hash = 1315423911,
i, l;
for( i = 0, l = str.length; i < l; i++ ){
hash ^= ((hash << 5) + str.charCodeAt(i) + (hash >> 2));
}
return (hash & 0x7FFFFFFF).toString(16);
},
PJW: function(str){
var bitsInUnsignedInt = 4 * 8,
threeQuarters = (bitsInUnsignedInt * 3) / 4,
oneEighth = bitsInUnsignedInt / 8,
highBits = 0xFFFFFFFF << (bitsInUnsignedInt - oneEighth),
hash = 0,
test = 0,
i,l;
for (i = 0, l = str.length; i < l; i++) {
hash = (hash << oneEighth) + str.charCodeAt(i);
}
if ((test = hash & highBits) !== 0) {
hash = (hash ^ (test >> threeQuarters)) & ~highBits;
}
return (hash & 0x7FFFFFFF).toString(16);
},
ELF: function(str){
var hash = 0,
x = 0,
i,l;
for( i = 0, l = str.length; i < l; i++ ){
hash = (hash << 4) + str.charCodeAt(i);
if ((x = hash & 0xF0000000) !== 0){
hash ^= (x >> 24);
hash &= ~x;
}
}
return (hash & 0x7FFFFFFF).toString(16);
},
BKDR: function(str){
var seed = 131,
hash = 0,
i,l;
for( i = 0, l = str.length; i < l; i++ ){
hash = hash * seed + str.charCodeAt(i);
hash &= 0x7FFFFFFF;
}
return hash.toString(16);
},
DJB: function(str){
var hash = 5381,
i,l;
for( i = 0, l = str.length; i < l; i++ ){
hash += (hash << 5) + str.charCodeAt(i);
}
return (hash & 0x7FFFFFFF).toString(16);
},
AP: function(str){
var hash = 0,
i,l;
for( i = 0, l = str.length; i < l; i++ ){
if( i%1 ){
hash ^= (~((hash << 11) ^ str.charCodeAt(i) ^ (hash >> 5)));
} else {
hash ^= ((hash << 7) ^ str.charCodeAt(i) ^ (hash >> 3));
}
}
return (hash & 0x7FFFFFFF).toString(16);
}
};
return strHash;
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment