unique.spec.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { describe, expect, it } from 'vitest';
  2. import { unique } from './unique';
  3. describe('unique()', () => {
  4. it('works with primitive values', () => {
  5. expect(unique([1, 1, 2, 3, 2, 6, 4, 2])).toEqual([1, 2, 3, 6, 4]);
  6. expect(unique(['a', 'f', 'g', 'f', 'y'])).toEqual(['a', 'f', 'g', 'y']);
  7. expect(unique([null, null, 1, 'a', 1])).toEqual([null, 1, 'a']);
  8. });
  9. it('works with object references', () => {
  10. const a = { a: true };
  11. const b = { b: true };
  12. const c = { c: true };
  13. expect(unique([a, b, a, b, c, a])).toEqual([a, b, c]);
  14. expect(unique([a, b, a, b, c, a])[0]).toBe(a);
  15. expect(unique([a, b, a, b, c, a])[1]).toBe(b);
  16. expect(unique([a, b, a, b, c, a])[2]).toBe(c);
  17. });
  18. it('works with object key param', () => {
  19. const a = { id: 'a', a: true };
  20. const b = { id: 'b', b: true };
  21. const c = { id: 'c', c: true };
  22. const d = { id: 'a', d: true };
  23. expect(unique([a, b, a, b, d, c, a], 'id')).toEqual([a, b, c]);
  24. });
  25. it('works an empty array', () => {
  26. expect(unique([])).toEqual([]);
  27. });
  28. it('perf on primitive array', () => {
  29. const bigArray = Array.from({ length: 50000 }).map(() => Math.random().toString().substr(2, 5));
  30. const timeStart = new Date().getTime();
  31. unique(bigArray);
  32. const timeEnd = new Date().getTime();
  33. expect(timeEnd - timeStart).toBeLessThan(100);
  34. });
  35. it('perf on object array', () => {
  36. const bigArray = Array.from({ length: 50000 })
  37. .map(() => Math.random().toString().substr(2, 5))
  38. .map(id => ({ id }));
  39. const timeStart = new Date().getTime();
  40. unique(bigArray, 'id');
  41. const timeEnd = new Date().getTime();
  42. expect(timeEnd - timeStart).toBeLessThan(100);
  43. });
  44. });