// https://gist.github.com/tkrotoff/f3f36926edeeb3f4ce4411151bde37b2 // Exported for testing purposes only // https://stackoverflow.com/a/45736131 export function getNumberWithDecimalPlaces(num: number, decimalPlaces: number) { const power = 10 ** decimalPlaces; return Math.floor(num * power) / power; } type GetRandomNumberOptions = { /** * The number of digits to appear after the decimal point. * https://ell.stackexchange.com/q/141863 */ decimalPlaces?: number; }; /** * Generates a pseudo-random float (0.3546, 5.8557...) between min (included) and max (excluded). */ export function getRandomFloat(min: number, max: number, options: GetRandomNumberOptions = {}) { const { decimalPlaces } = options; const num = Math.random() * (max - min) + min; if (decimalPlaces === undefined) { return num; } return getNumberWithDecimalPlaces(num, decimalPlaces); } /** * Generates a pseudo-random integer (0, 6...) between min (included) and max (included). */ export function getRandomInt(min: number, max: number) { // https://stackoverflow.com/a/7228322 return Math.floor(Math.random() * (max - min + 1)) + min; }