improve weightedRandom() handling of bad data input

update allowed param types, should only be arrays
This commit is contained in:
Dev 2023-12-01 17:22:24 +00:00
parent 52b91cae87
commit 19f6bbaed4

View File

@ -42,18 +42,23 @@ export class WeightedRandomHelper
* @param {number[]} weights
* @returns {{item: any, index: number}}
*/
public weightedRandom(items: string | any[], weights: string | any[]): { item: any; index: number; }
public weightedRandom(items: any[], weights: any[]): { item: any; index: number; }
{
if (!items || items.length === 0)
{
throw new Error("Items must not be empty");
}
if (!weights || weights.length === 0)
{
throw new Error("Item weights must not be empty");
}
if (items.length !== weights.length)
{
throw new Error("Items and weight inputs must be of the same length");
}
if (!items.length)
{
throw new Error("Items must not be empty");
}
// Preparing the cumulative weights array.
// For example:
// - weights = [1, 4, 3]