unique.spec.ts 1.8 KB

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