Last active
January 3, 2025 06:47
-
-
Save ardislu/dd6344d1f0485900619e044ad372a4ae to your computer and use it in GitHub Desktop.
Simple, small, and fast pseudorandom number generator to deterministically generate large amounts of mock test data.
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
/** | |
* Simple, small, and fast pseudorandom number generator to deterministically generate large amounts of mock test data. | |
* | |
* API is intended to follow [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues). | |
* | |
* Hash function source: | |
* - https://burtleburtle.net/bob/hash/integer.html | |
* - https://web.archive.org/web/20090408063205/http://www.cris.com/~Ttwang/tech/inthash.htm | |
* @param {ArrayBufferView<ArrayBufferLike>} typedArray An integer-based `TypedArray` with a byte length that is a multiple of 4. | |
* All elements in the array will be overwritten with random numbers. | |
* @param {Number} seed A number to initiate the pseudorandom hash function. | |
* @returns {ArrayBufferView<ArrayBufferLike>} The same array passed as `typedArray` but with its contents replaced with pseudorandom | |
* numbers. Note that `typedArray` is modified in-place and no copy is made. | |
*/ | |
function getPseudoRandomValues(typedArray, seed) { | |
function hash(n) { | |
n = n ^ (n >> 4); | |
n = (n ^ 0xdeadbeef) + (n << 5); | |
n = n ^ (n >> 11); | |
return n; | |
} | |
const array = new Uint32Array(typedArray.buffer); | |
let h = hash(seed); | |
for (let i = 0; i < array.length; i++) { | |
h = hash(h); | |
array[i] = h; | |
} | |
return typedArray; | |
} | |
// Usage example: | |
// const arr = new Uint8Array(1024 * 1024 * 1024); | |
// getPseudoRandomValues(arr, 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment