sample

import { sample } from "jsr:@ende/random";

function ยท experimental

function sample<T>(array: ArrayLike<T>, options?: SampleOptions): T | undefined

Returns a random element from the given array.

array: ArrayLike<T>

The array to sample from.

options?: SampleOptions

Options modifying the sampling behavior.

Returns

A random element from the given array, or undefined if the array is empty.

Example: Basic usage

import { sample } from "@ende/random/sample";
import { assertArrayIncludes } from "@ende/assert";

const numbers = [1, 2, 3, 4];
const sampled = sample(numbers);

assertArrayIncludes(numbers, [sampled]);

Example: Using weights option

import { sample } from "@ende/random/sample";

const values = ["a", "b", "c"];
const weights = [5, 3, 2];
const result = sample(values, { weights });
// gives "a" 50% of the time, "b" 30% of the time, and "c" 20% of the time

Source