1
0

array.spec.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { describe, expect, it } from "vitest";
  2. import { randomItem, randomItemIndex, randomizeArray, takeRandomItem } 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 takeRandomItem
  32. describe("array/takeRandomItem", () => {
  33. it("Returns a random item and removes it from the array", () => {
  34. const arr = [1, 2];
  35. const itm = takeRandomItem(arr);
  36. expect(arr).not.toContain(itm);
  37. takeRandomItem(arr);
  38. const itm2 = takeRandomItem(arr);
  39. expect(itm2).toBeUndefined();
  40. expect(arr).toHaveLength(0);
  41. });
  42. it("Returns undefined for an empty array", () => {
  43. expect(takeRandomItem([])).toBeUndefined();
  44. });
  45. });
  46. //#region randomizeArray
  47. describe("array/randomizeArray", () => {
  48. it("Returns a copy of the array with a random item order", () => {
  49. const arr = Array.from({ length: 100 }, (_, i) => i);
  50. const randomized = randomizeArray(arr);
  51. expect(randomized === arr).toBe(false);
  52. expect(randomized).toHaveLength(arr.length);
  53. const sameItems = arr.filter((item, i) => randomized[i] === item);
  54. expect(sameItems.length).toBeLessThan(arr.length);
  55. });
  56. it("Returns an empty array as-is", () => {
  57. const arr = [] as number[];
  58. const randomized = randomizeArray(arr);
  59. expect(randomized === arr).toBe(false);
  60. expect(randomized).toHaveLength(0);
  61. });
  62. });