UNPKG

everyutil

Version:

A comprehensive library of lightweight, reusable utility functions for JavaScript and TypeScript, designed to streamline common programming tasks such as string manipulation, array processing, date handling, and more.

22 lines (21 loc) 816 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.weightedRandom = void 0; /** * Returns a random choice from the input choices array, using the given weights. * @author @dailker * @param {number[]} choices - The array of possible choices. * @param {number[]} weights - The array of weights corresponding to each choice. * @returns {number} A randomly selected value from choices, weighted by weights. */ function weightedRandom(choices, weights) { const sum = weights.reduce((a, b) => a + b, 0); let r = Math.random() * sum; for (let i = 0; i < choices.length; i++) { if (r < weights[i]) return choices[i]; r -= weights[i]; } return choices[choices.length - 1]; } exports.weightedRandom = weightedRandom;