// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { randomInteger } from "./_utils.ts";

/**
 * Returns a random element from the given array.
 *
 * @template T The type of the elements in the array.
 * @template O The type of the accumulator.
 *
 * @param array The array to sample from.
 *
 * @returns A random element from the given array, or `undefined` if the array
 * is empty.
 *
 * @example Basic usage
 * ```ts
 * import { sample } from "@std/collections/sample";
 * import { assertArrayIncludes } from "@std/assert/assert-array-includes";
 *
 * const numbers = [1, 2, 3, 4];
 * const random = sample(numbers);
 *
 * assertArrayIncludes(numbers, [random]);
 * ```
 */
export function sample<T>(array: readonly T[]): T | undefined {
  const length = array.length;
  return length ? array[randomInteger(0, length - 1)] : undefined;
}

// denoCacheMetadata={"headers":{"report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=Z6u9OFhhwlBS5xuyQIFAfVbGbqCahnYRM7eB1aoJeLprcnsRfx82eQ331EbmzSUje%2BadUskHXqUjtGmffGFF6%2FBp41%2B%2F32VcKm8kM%2BPHgABku42wMYJtg40%3D\"}]}","cf-ray":"a223e6564f347db6-LAX","alt-svc":"h3=\":443\"; ma=86400","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","server":"cloudflare","access-control-allow-origin":"*","x-content-type-options":"nosniff","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","x-robots-tag":"noindex","content-length":"912","etag":"\"ee4b9a0517dbc6fdfb218b15c51ccf9c\"","vary":"Origin","cache-control":"public, max-age=31536000, immutable","cross-origin-resource-policy":"cross-origin","date":"Tue, 28 Jul 2026 12:31:15 GMT","content-type":"text/typescript","x-jsr-backend":"modules","set-cookie":"__cf_bm=hbURcvwvg9ysikkr5DVf5i1RfpWblo2_.LdraFCliUQ-1785241874.9640994-1.0.1.1-wdrwiCe0C2dDArSqQMFbtA5ivly.YUGJKzA5_lgWeiicjKcamJdc9.KZGS4IJXorirGXPq0HnU6Sq9bPYI3U9gSsOUtQRlGMuqhMhofYbhG7oEAzOiQe8uZS5wf_DiBx; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","access-control-expose-headers":"*"},"url":"https://jsr.io/@std/collections/0.224.2/sample.ts","time":1785241875}