1
0

array.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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((randRange(0, 10000) / 10000) * (i + 1));
  38. // @ts-ignore
  39. [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
  40. }
  41. return retArray;
  42. }