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);
}
阅读 2.1k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题