array.spec.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { describe, expect, it } from "vitest";
  2. import { randomItem, randomItemIndex, randomizeArray } from "./array.js";
  3. //#region randomItem
  4. describe("array/randomItem", () => {
  5. it("Returns a random item", () => {
  6. const arr = [1, 2, 3, 4];
  7. const items = [] as number[];
  8. for(let i = 0; i < 500; i++)
  9. items.push(randomItem(arr)!);
  10. const missing = arr.filter(item => !items.some(i => i === item));
  11. expect(missing).toHaveLength(0);
  12. });
  13. it("Returns undefined for an empty array", () => {
  14. expect(randomItem([])).toBeUndefined();
  15. });
  16. });
  17. //#region randomItemIndex
  18. describe("array/randomItemIndex", () => {
  19. it("Returns a random item with the correct index", () => {
  20. const arr = [1, 2, 3, 4];
  21. const items = [] as [number, number][];
  22. for(let i = 0; i < 500; i++)
  23. items.push(randomItemIndex(arr) as [number, number]);
  24. const missing = arr.filter((item, index) => !items.some(([it, idx]) => it === item && idx === index));
  25. expect(missing).toHaveLength(0);
  26. });
  27. it("Returns undefined for an empty array", () => {
  28. expect(randomItemIndex([])).toEqual([undefined, undefined]);
  29. });
  30. });
  31. //#region randomizeArray
  32. describe("array/randomizeArray", () => {
  33. it("Returns a copy of the array with a random item order", () => {
  34. const arr = Array.from({ length: 100 }, (_, i) => i);
  35. const randomized = randomizeArray(arr);
  36. expect(randomized === arr).toBe(false);
  37. expect(randomized).toHaveLength(arr.length);
  38. const sameItems = arr.filter((item, i) => randomized[i] === item);
  39. expect(sameItems.length).toBeLessThan(arr.length);
  40. });
  41. it("Returns an empty array as-is", () => {
  42. const arr = [] as number[];
  43. const randomized = randomizeArray(arr);
  44. expect(randomized === arr).toBe(false);
  45. expect(randomized).toHaveLength(0);
  46. });
  47. });