Towards an JS xor128
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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