Created
January 26, 2018 19:52
-
-
Save brianchirls/3ddcd2c552d12f03df807ffc4c839627 to your computer and use it in GitHub Desktop.
Repeatable pseudo-random number generator based on predictable input values
This file contains hidden or 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
import hash from 'string-hash'; | |
function stringHash(s) { | |
if (s.length === 1) { | |
return s.charCodeAt(0); | |
} | |
return hash(s); | |
} | |
function random(initial) { | |
let seed = (initial | 0) + 0x2F6E2B1; | |
seed = (seed + 0x7ED55D16 + seed << 12) & 0xFFFFFFFF; | |
seed = (seed ^ 0xC761C23C ^ seed >>> 19) & 0xFFFFFFFF; | |
seed = (seed + 0x165667B1 + seed << 5) & 0xFFFFFFFF; | |
seed = (seed + 0xD3A2646C ^ seed << 9) & 0xFFFFFFFF; | |
seed = (seed + 0xFD7046C5 + seed << 3) & 0xFFFFFFFF; | |
seed = (seed ^ 0xB55A4F09 ^ seed >>> 16) & 0xFFFFFFFF; | |
return (seed & 0xFFFFFFF) / 0x10000000; | |
} | |
// example, getting random seed from row index, field id and data value | |
const valueSeed = typeof value === 'number' ? value : stringHash(String(value)); | |
console.log(random(Math.floor(fieldId) + Math.floor(rowIndex) + valueSeed)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment