UNPKG

random-pie

Version:

A lightweight TypeScript/JavaScript library providing Python-style random number generation and randomization utilities. This utility module implements the most common functions from Python's random module, making it intuitive for Python developers workin

59 lines (58 loc) 2.63 kB
import { ChoicesOptions } from "./types"; /** * Return a random element from the given array. * * @param {Array} arr The input array * @throws TypeError if the given argument is not an array * @throws RangeError if the given array is empty * @returns {*} An element from the given array */ declare function choice<T>(arr: T[]): T; /** * Return a list of randomly selected elements from the given array. * * @param {Array} arr The input array * @param {Object} [options] Configuration options for selection * @param {Array} [options.weights=null] An array of weights corresponding to each element in arr * @param {Array} [options.cumWeights=null] An array of cumulative weights * @param {number} [options.k=1] The number of elements to select * @throws TypeError if the first argument is not an array * @throws RangeError if the array is empty * @throws TypeError if k is not a non-negative integer * @throws TypeError if weights or cumWeights are not arrays * @throws RangeError if weights or cumWeights length does not match array length * @throws RangeError if weights contain negative values * @throws RangeError if weights contain only zeros * @returns {Array} An array containing k randomly selected elements */ declare function choices<T>(arr: T[], { weights, cumWeights, k }?: ChoicesOptions): T[]; /** * Shuffles the given array in place. * * @param {Array} arr The input array * @throws TypeError if the given argument is not an array */ declare function shuffle<T>(arr: T[]): void; /** * Returns a shuffled copy of the given array. * * @param {Array} arr The input array * @throws TypeError if the given argument is not an array * @returns {Array} A new array with the same elements, in a random order */ declare function shuffled<T>(arr: T[]): T[]; /** * Returns k unique elements chosen from the population sequence. If k is larger than * the population size, raise a RangeError. If counts is given, elements from the * population are selected according to the given weights. If the relative weights are * not specified, the selections are made with equal probability. * * @param {Array} arr The population sequence * @param {number} k The number of elements to choose * @param {Array<number>=} counts The weights for each element in the population * @throws TypeError if the given arguments are invalid * @throws RangeError if k is larger than the population size * @returns {Array} A list of k unique elements from the population */ declare function sample<T>(arr: T[], k: number, counts?: number[] | null): T[]; export { choice, choices, shuffle, shuffled, sample };