Files
arubinochan-bot/lib/util.ts
2025-10-02 09:50:48 +00:00

17 lines
630 B
TypeScript

/** pick up to random N elements from array.
* just shuffle it if N is unspecified or greater than the length of the array.
* the original array remains unmodified. */
export function sample<T>(arr: T[], n: number = arr.length): T[] {
if (n > arr.length) return sample(arr, arr.length);
const copy = [...arr];
for (let i = 0; i < n; i++) {
const j = i + Math.floor(Math.random() * (copy.length - i));
[copy[i], copy[j]] = [copy[j] as T, copy[i] as T];
}
return copy.slice(0, n);
}
/** sleep for N milliseconds */
export const sleep = (msec: number) =>
new Promise((resolve) => setTimeout(resolve, msec));