skip to Main Content

How to calculate hash code for N hash codes? To calculate hash code for the collection like Array?

Number.prototype.hashCode = function() { return this }
String.prototype.hashCode = function() { return cyrb53(this) }
Array.prototype.hashCode  = function() { ??? }

It’s not for security, for hashing etc. so something similar to Java hashCode would be ok.

P.S.

If that matters, for Number hash code is same as the number itself, for String cyrb53 from Generate a Hash from string in Javascript

2

Answers


  1. Chosen as BEST ANSWER

    I convert Nim !& Hash operator to JS

    function Hashes(seed = 0) { return {
      code: seed,
      add (code) {
        this.code = this.code + code
        this.code = this.code + (this.code << 10)
        this.code = this.code ^ (@code >>> 6)
      }
    }}
    
    h = Hashes()
    h.add('a'.hashCode())
    h.add('b'.hashCode())
    console.log(h.code)
    

    Original Nim code

    proc `!&`*(h: Hash, val: int): Hash {.inline.} =
      ## Mixes a hash value `h` with `val` to produce a new hash value.
      ##
      ## This is only needed if you need to implement a `hash` proc for a new datatype.
      let h = cast[uint](h)
      let val = cast[uint](val)
      var res = h + val
      res = res + res shl 10
      res = res xor (res shr 6)
      result = cast[Hash](res)
    

  2. You’re gonna have to hash the contents of the array anyway, so you might as well stringify the whole thing:

    Number.prototype.hashCode = function() { return this }
    String.prototype.hashCode = function() { return cyrb53(this) }
    Array.prototype.hashCode  = function() { return JSON.stringify(this).hashCode(); }
    
    const cyrb53 = (str, seed = 0) => {let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;for(let i = 0, ch; i < str.length; i++) {ch = str.charCodeAt(i);h1 = Math.imul(h1 ^ ch, 2654435761);h2 = Math.imul(h2 ^ ch, 1597334677);}h1  = Math.imul(h1 ^ (h1 >>> 16), 2246822507);h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);h2  = Math.imul(h2 ^ (h2 >>> 16), 2246822507);h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);return 4294967296 * (2097151 & h2) + (h1 >>> 0);};
    
    console.log([1,2,3].hashCode());
    console.log([3,2,1].hashCode());
    console.log(['foo', 'bar'].hashCode());
    console.log(['bar', 'foo'].hashCode());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search