Created
December 19, 2023 11:16
-
-
Save yornaath/d5a65a3fd89501dc1219294cf7587fa1 to your computer and use it in GitHub Desktop.
Pseudo random deterministic choice
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
import seedrandom from "seedrandom"; | |
/** | |
* Pseudo-random number generator that returns a number between min and max deterministically based on a seed. | |
* | |
* @param seed string | |
* @param min min range value | |
* @param max max range value | |
* @returns number | |
*/ | |
export const seededRandomRangedInt = ( | |
seed: string, | |
min: number, | |
max: number, | |
) => { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
const rng = seedrandom(seed); | |
return Math.floor(rng() * (max - min + 1)) + min; | |
}; | |
/** | |
* Deterministically returns a random element from an array of choices based on a seed. | |
* | |
* @param seed string | |
* @param choices T[] | |
* @returns T | |
*/ | |
export const seededChoice = <T>(seed: string, choices: T[]): T => { | |
const index = seededRandomRangedInt(seed, 0, choices.length - 1); | |
return choices[index]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment