Skip to content

Instantly share code, notes, and snippets.

@jaredly
Created October 31, 2023 17:59
Show Gist options
  • Save jaredly/82ebbcc6195785d3dca3683859e61999 to your computer and use it in GitHub Desktop.
Save jaredly/82ebbcc6195785d3dca3683859e61999 to your computer and use it in GitHub Desktop.
murmurhash3 64bit
const as64 = (n) => BigInt.asUintN(64, n);
const murmur_m = BigInt('0xc6a4a7935bd1e995')
const murmur_r = 47n
const defaultSeed = BigInt('0xdeadbeef');
const hash64End = (h) => {
let h1 = xor(h, shiftR(h, murmur_r)),
h2 = as64(h1 * murmur_m),
h3 = xor(h2, shiftR(h2, murmur_r));
return h3
}
const hash64WithSeed = (seed, a) => hash64End(hash64Add(a, seed))
const hash64 = (v) => hash64WithSeed(defaultSeed, v)
const xor = (a, b) => as64(a ^ b)
const shiftR = (a, b) => as64(a >> b)
const tr = (m, v) => {
console.log([m, v])
return v
}
const hash64AddWord64 = (k,h) => {
let k1 = as64(BigInt(k) * murmur_m),
k2 = xor(k1, shiftR(k1, murmur_r)),
k3 = as64(k2 * murmur_m),
h1 = as64(h * murmur_m),
h2 = xor(h1, k3)
return h2
}
const hash64Add = (bytes, initial) => {
const go = (acc, b) => hash64AddWord64(b, acc)
return bytes.reduce(go, hash64AddWord64(9, initial))
}
const ok = Buffer.from('hello')
const res = hash64(ok)
console.log(res)
console.log('0x' + res.toString(16))
const ok2 = Buffer.from('000000030304010568656c6c6f', 'hex')
console.log(hash64(ok2), '0x' + hash64(ok2).toString(16))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment