immutablejs源码中这个计算字符串哈希的算法的怎么理解?
immutablejs源码中这个计算字符串哈希的算法的怎么理解?就算官方给出数学公式和解释也理解不了啊,它应该只是计算字符串的唯一hash值的吧?为什么这么算能得到唯一的值?
// http://jsperf.com/hashing-strings
function hashString(string) {
// This is the hash from JVM
// The hash code for a string is computed as
// s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
// where s[i] is the ith character of the string and n is the length of
// the string. We "mod" the result to make it between 0 (inclusive) and 2^31
// (exclusive) by dropping high bits.
var hash = 0;
for (var ii = 0; ii < string.length; ii++) {
hash = 31 * hash + string.charCodeAt(ii) | 0;
}
return smi(hash);
}
// v8 has an optimization(优化组合) for storing 31-bit signed numbers(有正负符号数).
// Values which have either 00 or 11 as the high order bits(高字节位) qualify(限定).
// This function drops the highest order bit in a signed number(有正负符号数), maintaining(坚持,保卫)
// the sign bit(符号位).
function smi(i32) {
return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论