Last active
November 3, 2025 14:45
-
-
Save steveruizok/09a1d3ff88175b077f9affbee1d4ce73 to your computer and use it in GitHub Desktop.
Seeded random number generator in TypeScript.
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
| /** | |
| * Seeded random number generator, using [xorshift](https://en.wikipedia.org/wiki/Xorshift). | |
| * Adapted from [seedrandom](https://github.com/davidbau/seedrandom). | |
| * @param seed {string} The seed for random numbers. | |
| */ | |
| function rng(seed = '') { | |
| let x = 0 | |
| let y = 0 | |
| let z = 0 | |
| let w = 0 | |
| function next() { | |
| const t = x ^ (x << 11) | |
| x = y | |
| y = z | |
| z = w | |
| w ^= ((w >>> 19) ^ t ^ (t >>> 8)) >>> 0 | |
| return w / 0x100000000 | |
| } | |
| for (var k = 0; k < seed.length + 64; k++) { | |
| x ^= seed.charCodeAt(k) | 0 | |
| next() | |
| } | |
| return next | |
| } | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This random number generator is "seeded". This means that the random numbers it generates will be the same for identical seeds, allowing randomization to be consistent between sessions. In my use case, shapes on a canvas need to be slightly wonky, however the shape's wonkiness needs to be consistent for that shape.
In the above example, the function returned by
rng("someId")will always produce-0.1967178131453693when called the first time,0.2110769241116941when called the second time, and so on. You can try it yourself: you'll get the same results.A different seed will produce different results.