small array utilities
0

Configure Feed

Select the types of activity you want to include in your feed.

feat: weightedIndex

+34
+34
lib/mod.ts
··· 269 269 270 270 return result.reverse(); 271 271 }; 272 + 273 + /** 274 + * randomly selects an index based on weights 275 + * @param weights array of weights (numbers) 276 + * @returns random index selected based on weight distribution or -1 if array is empty 277 + */ 278 + /*#__NO_SIDE_EFFECTS__*/ 279 + export const weightedIndex = (weights: number[]): number => { 280 + const len = weights.length; 281 + 282 + const arr = new Array(len); 283 + let total = 0; 284 + 285 + for (let i = 0; i < len; i++) { 286 + const weight = Math.max(0, weights[i]); 287 + arr[i] = weight; 288 + total += weight; 289 + } 290 + 291 + if (total <= 0) { 292 + return -1; 293 + } 294 + 295 + let rand = Math.random() * total; 296 + for (let i = 0; i < len; i++) { 297 + rand -= arr[i]; 298 + 299 + if (rand < 0) { 300 + return i; 301 + } 302 + } 303 + 304 + return len - 1; 305 + };