BUGFIX: Improve implementation of getRandomInt (#1282)

This commit is contained in:
catloversg
2024-05-19 05:12:06 +07:00
committed by GitHub
parent 8deb907b89
commit 175af0bd28
20 changed files with 160 additions and 130 deletions
+2 -2
View File
@@ -4,7 +4,7 @@ import type { NetscriptContext } from "../Netscript/APIWrapper";
import * as allEnums from "../Enums";
import { assertString } from "../Netscript/TypeAssertion";
import { errorMessage } from "../Netscript/ErrorMessages";
import { getRandomInt } from "./helpers/getRandomInt";
import { getRandomIntInclusive } from "./helpers/getRandomIntInclusive";
interface GetMemberOptions {
/** Whether to use fuzzy matching on the input (case insensitive, ignore spaces and dashes) */
@@ -69,7 +69,7 @@ class EnumHelper<EnumObj extends object, EnumMember extends Member<EnumObj> & st
}
// Get a random enum member
random() {
const index = getRandomInt(0, this.valueArray.length - 1);
const index = getRandomIntInclusive(0, this.valueArray.length - 1);
return this.valueArray[index];
}
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { getRandomInt } from "./getRandomInt";
import { getRandomIntInclusive } from "./getRandomIntInclusive";
/**
* Gets a random value in the range of a byte (0 - 255), or up to the maximum.
@@ -9,5 +9,5 @@ export function getRandomByte(max: number): number {
const byteMaximum = 255;
const upper: number = Math.max(Math.min(max, byteMaximum), 0);
return getRandomInt(0, upper);
return getRandomIntInclusive(0, upper);
}
-11
View File
@@ -1,11 +0,0 @@
/**
* Gets a random integer bounded by the values passed in.
* @param min The minimum value in the range.
* @param max The maximum value in the range.
*/
export function getRandomInt(min: number, max: number): number {
const lower: number = Math.min(min, max);
const upper: number = Math.max(min, max);
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
}
@@ -0,0 +1,21 @@
/**
*
* Gets a random integer between min (inclusive) and max (inclusive).
*
* Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
*
* @param min The minimum value in the range.
* @param max The maximum value in the range.
*/
export function getRandomIntInclusive(min: number, max: number): number {
if (!Number.isInteger(min)) {
throw new Error(`Min is not an integer. Min: ${min}.`);
}
if (!Number.isInteger(max)) {
throw new Error(`Max is not an integer. Max: ${max}.`);
}
if (min > max) {
throw new Error(`Min is greater than max. Min: ${min}. Max: ${max}.`);
}
return Math.floor(Math.random() * (max - min + 1) + min);
}