sample

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

function

function sample<T>(iterable: Iterable<T>): T | undefined

Returns a random element from the given iterable.

iterable: Iterable<T>

The iterable to sample from.

Returns

A random element from the given iterable, or undefined if the iterable has no elements.

Example: Basic usage

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

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

assertArrayIncludes(numbers, [random]);

Source