Skip to content

Instantly share code, notes, and snippets.

@keelii
Forked from mtmzorro/getHashCode.js
Created October 16, 2013 10:52
Show Gist options
  • Save keelii/7005967 to your computer and use it in GitHub Desktop.
Save keelii/7005967 to your computer and use it in GitHub Desktop.
/**
* 获取字符串的哈希值
* @param {String} str
* @param {Boolean} caseSensitive
* @return {Number} hashCode
*/
getHashCode:function(str,caseSensitive){
if(!caseSensitive){
str = str.toLowerCase();
}
// 1315423911=b'1001110011001111100011010100111'
var hash = 1315423911,i,ch;
for (i = str.length - 1; i >= 0; i--) {
ch = str.charCodeAt(i);
hash ^= ((hash << 5) + ch + (hash >> 2));
}
return (hash & 0x7FFFFFFF);
}
/**
* JS中实现JAVA的hashCode算法
* @param {String} str
* @return {Number} hashCode
*/
function hashCode(str){
var h = 0, off = 0;
var len = str.length;
for(var i = 0; i < len; i++){
h = 31 * h + str.charCodeAt(off++);
}
var t=-2147483648*2;
while(h>2147483647){
h+=t
}
return h;
}
/**
* String hash code
* @param {String} str
* @return {int}
*/
function hashCode(str) {
for (var result = 0, i = 0; i < str.length; i++) {
result = (result << 5) - result + str.charCodeAt(i);
result &= result;
}
return result;
}
// Compressed
function(e){for(var r=0,i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r&=r;return r};
// Usage
console.log(hashCode("Secret message"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment