From 19f6bbaed4c1d640e3e613002570bfb355639e88 Mon Sep 17 00:00:00 2001 From: Dev Date: Fri, 1 Dec 2023 17:22:24 +0000 Subject: [PATCH] improve `weightedRandom()` handling of bad data input update allowed param types, should only be arrays --- project/src/helpers/WeightedRandomHelper.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/project/src/helpers/WeightedRandomHelper.ts b/project/src/helpers/WeightedRandomHelper.ts index da9dcf3e..4c3ba03c 100644 --- a/project/src/helpers/WeightedRandomHelper.ts +++ b/project/src/helpers/WeightedRandomHelper.ts @@ -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]