Function sample

  • Experimental

    Returns a random element from the given array.

    UNSTABLE: New API, yet to be vetted.

    Type Parameters

    • T

      The type of the elements in the array.

    Parameters

    • array: ArrayLike<T>

      The array to sample from.

    • Optionaloptions: SampleOptions

      Options modifying the sampling behavior.

    Returns T | undefined

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

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

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

    assertArrayIncludes(numbers, [sampled]);
    import { sample } from "@std/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