【发布时间】:2018-08-04 12:26:06
【问题描述】:
我正在研究 javascript 中 hasmap 的哈希字符串函数。并查看我在网上找到的这段代码,我不确定该函数是否正确:
HashMap._hashString = function(string) {
var hash = 5381;
for (var i=0; i<string.length; i++) {
hash = (hash << 5) + hash + string.charCodeAt(i);
hash = hash & hash;
}
//Reduce the chance of collisions by incorporating the string length,
//and randomize the hashes to prevent malicious collisions.
return hash ^ string.length ^ this._secret;
};
有这条线有意义吗?
hash = hash & hash;
在这行代码中:
return hash ^ string.length ^ this._secret;
我知道添加字符串的长度作为哈希评估的一个因素将有助于处理冲突,但为什么我要使用 XOR 操作添加这个因素?为什么不使用任何其他位运算符?
我也在阅读这篇文章,以了解更多关于哈希算法的信息:
【问题讨论】:
标签: javascript algorithm hash