02月17, 2017

Java 与 JS 分别对 hashCode 的实现

Java 与 JS 对 hashCode 的实现:

hashCode

JDK String 类已经实现了 hashCode , 代码如下. 现在有需求 JS 实现对设备 xxID 的 hashCode, 为了与大数据统计保持一致, 需要保持一样的算法, 代码比 Java 代码还优雅.

/**
 * Returns a hash code for this string. The hash code for a
 * <code>String</code> object is computed as
 * <blockquote><pre>
 * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
 * </pre></blockquote>
 * using <code>int</code> arithmetic, where <code>s[i]</code> is the
 * <i>i</i>th character of the string, <code>n</code> is the length of
 * the string, and <code>^</code> indicates exponentiation.
 * (The hash value of the empty string is zero.)
 *
 * @return  a hash code value for this object.
 */
public int hashCode() {
  int h = hash;
  if (h == 0 && value.length > 0) {
    char val[] = value;
    for (int i = 0; i < value.length; i++) {
      h = 31 * h + val[i];
    }
    hash = h;
  }
  return h;
}

为了保持一致的, JS对应实现如下:

String.prototype.hashCode = function() {
  var hash = 0, i, chr, len;
  if (this.length === 0) return hash;
  for (i = 0, len = this.length; i < len; i++) {
    chr   = this.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0;
  }
  return hash;
};

http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/

本文链接:https://www.javapk.net/post/java-and-js-hashcode.html

-- EOF --