array.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @module lib/array
  3. * This module contains various functions for working with arrays - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#arrays)
  4. */
  5. import { randRange } from "./math.js";
  6. /** Describes an array with at least one item */
  7. export type NonEmptyArray<TArray = unknown> = [TArray, ...TArray[]];
  8. /** Returns a random item from the passed array */
  9. export function randomItem<TItem = unknown>(array: TItem[]): TItem | undefined {
  10. return randomItemIndex<TItem>(array)[0];
  11. }
  12. /**
  13. * Returns a tuple of a random item and its index from the passed array
  14. * Returns `[undefined, undefined]` if the passed array is empty
  15. */
  16. export function randomItemIndex<TItem = unknown>(array: TItem[]): [item?: TItem, index?: number] {
  17. if(array.length === 0)
  18. return [undefined, undefined];
  19. const idx = randRange(array.length - 1);
  20. return [array[idx]!, idx];
  21. }
  22. /** Returns a random item from the passed array and mutates the array to remove the item */
  23. export function takeRandomItem<TItem = unknown>(arr: TItem[]): TItem | undefined {
  24. const [itm, idx] = randomItemIndex<TItem>(arr);
  25. if(idx === undefined)
  26. return undefined;
  27. arr.splice(idx, 1);
  28. return itm as TItem;
  29. }
  30. /** Returns a copy of the array with its items in a random order */
  31. export function randomizeArray<TItem = unknown>(array: TItem[]): TItem[] {
  32. const retArray = [...array]; // so array and retArray don't point to the same memory address
  33. if(array.length === 0)
  34. return retArray;
  35. // shamelessly stolen from https://javascript.info/task/shuffle
  36. for(let i = retArray.length - 1; i > 0; i--) {
  37. const j = Math.floor((Math.random() * (i + 1)));
  38. [retArray[i], retArray[j]] = [retArray[j], retArray[i]] as [TItem, TItem];
  39. }
  40. return retArray;
  41. }