array.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { randRange } from "./math";
  2. /** Returns a random item from the passed array */
  3. export function randomItem<T = unknown>(array: T[]) {
  4. return randomItemIndex<T>(array)[0];
  5. }
  6. /**
  7. * Returns a tuple of a random item and its index from the passed array
  8. * Returns `[undefined, undefined]` if the passed array is empty
  9. */
  10. export function randomItemIndex<T = unknown>(array: T[]): [item?: T, index?: number] {
  11. if(array.length === 0)
  12. return [undefined, undefined];
  13. const idx = randRange(array.length - 1);
  14. return [array[idx]!, idx];
  15. }
  16. /** Returns a random item from the passed array and mutates the array to remove the item */
  17. export function takeRandomItem<T = unknown>(arr: T[]) {
  18. const [itm, idx] = randomItemIndex<T>(arr);
  19. if(idx === undefined)
  20. return undefined;
  21. arr.splice(idx, 1);
  22. return itm as T;
  23. }
  24. /** Returns a copy of the array with its items in a random order */
  25. export function randomizeArray<T = unknown>(array: T[]) {
  26. const retArray = [...array]; // so array and retArray don't point to the same memory address
  27. if(array.length === 0)
  28. return array;
  29. // shamelessly stolen from https://javascript.info/task/shuffle
  30. for(let i = retArray.length - 1; i > 0; i--) {
  31. const j = Math.floor((randRange(0, 10000) / 10000) * (i + 1));
  32. // @ts-ignore
  33. [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
  34. }
  35. return retArray;
  36. }