Skip to content

Instantly share code, notes, and snippets.

@thewhodidthis
Last active November 8, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thewhodidthis/2c05fd7aa21e1c2ec6afd4360b3275b2 to your computer and use it in GitHub Desktop.
Save thewhodidthis/2c05fd7aa21e1c2ec6afd4360b3275b2 to your computer and use it in GitHub Desktop.
Towards an JS xor128
// This is half the maximum `Uint32Array` length, which I need to
// scale the output down to between 0 and 1.
// https://github.com/stdlib-js/constants-int32-max
const INT32_MAX = 2147483647
// https://en.wikipedia.org/wiki/Xorshift
export function xor128(seed = Math.random()) {
// Using the djb2 hashing function to initialise state.
// http://www.cse.yorku.ca/~oz/hash.html
const state = new Uint32Array(4).fill(5381)
const x = String(seed)
for (let i = 0; i < x.length; i += 1) {
const j = i % state.length
state[j] = Math.imul(state[j], 33) + x.charCodeAt(i)
}
return () => {
const [s,,,a] = state
const b = a ^ (a << 11)
const t = b ^ (b >> 8)
state[3] = state[2]
state[2] = state[1]
state[1] = s
state[0] = t ^ s ^ (s >> 19)
// Fit result between 0 and 1.
return state[0] / INT32_MAX
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment