All files / collections / unstable_sample.ts

100.00% Branches 4/4
100.00% Lines 14/14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x24
x24
x31
x24
x39
x39
x24
x24
x25
x25
x45
x45
x24





































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Returns a random element from the given iterable.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the elements in the iterable.
 *
 * @param iterable The iterable to sample from.
 *
 * @returns A random element from the given iterable, or `undefined` if the iterable has no elements.
 *
 * @example Basic usage
 * ```ts
 * import { sample } from "@std/collections/unstable-sample";
 * import { assertArrayIncludes } from "@std/assert";
 *
 * const numbers = [1, 2, 3, 4];
 * const random = sample(numbers);
 *
 * assertArrayIncludes(numbers, [random]);
 * ```
 */
export function sample<T>(iterable: Iterable<T>): T | undefined {
  let array: readonly T[];
  if (Array.isArray(iterable)) {
    array = iterable;
  } else {
    array = Array.from(iterable);
  }
  const length: number = array.length;
  if (length === 0) {
    return undefined;
  }
  const randomIndex = Math.floor(Math.random() * length);
  return array[randomIndex];
}