-1

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

Alex Craft
  • 13,598
  • 11
  • 69
  • 133
  • Have you tried using `JSON.stringify` on the Array and treat it as a string? – Kaddath Aug 30 '23 at 13:20
  • @Kaddath I hoped there is faster way to calculate hash than converting whole array to string :) – Alex Craft Aug 30 '23 at 13:21
  • I really don't think it will be that slow, maybe it will temporary use more memory than solutions looping over the array, but slow, it would surprise me, what use will the hashcode be for? (beware of premature optimization) – Kaddath Aug 30 '23 at 13:28

2 Answers2

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());
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
1

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)
Alex Craft
  • 13,598
  • 11
  • 69
  • 133