arrayUtils.test.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { describe, test, it, expect } from 'vitest'
  2. import ArrayUtils from '~/services/utils/arrayUtils'
  3. import DateUtils from '~/services/utils/dateUtils'
  4. describe('sort', () => {
  5. test('with integers', () => {
  6. expect(ArrayUtils.sort([2, 1, 3])).toEqual([1, 2, 3])
  7. expect(ArrayUtils.sort([2, 1, 3], true)).toEqual([3, 2, 1])
  8. })
  9. test('with string', () => {
  10. expect(ArrayUtils.sort(['b', 'a', 'c'])).toEqual(['a', 'b', 'c'])
  11. expect(ArrayUtils.sort(['b', 'a', 'c'], true)).toEqual(['c', 'b', 'a'])
  12. })
  13. test('with dates', () => {
  14. const input = [
  15. new Date(2023, 0, 12),
  16. new Date(2023, 0, 10),
  17. new Date(2023, 0, 11),
  18. ]
  19. const expected = [
  20. new Date(2023, 0, 10),
  21. new Date(2023, 0, 11),
  22. new Date(2023, 0, 12),
  23. ]
  24. const expectedReverse = [
  25. new Date(2023, 0, 12),
  26. new Date(2023, 0, 11),
  27. new Date(2023, 0, 10),
  28. ]
  29. expect(DateUtils.sort(input)).toEqual(expected)
  30. expect(DateUtils.sort(input, true)).toEqual(expectedReverse)
  31. })
  32. })
  33. describe('sortObjectsByProp', () => {
  34. test('existing prop', () => {
  35. const input = [
  36. { id: 2, name: 'b' },
  37. { id: 1, name: 'a' },
  38. { id: 3, name: 'c' },
  39. ]
  40. const expected = [
  41. { id: 1, name: 'a' },
  42. { id: 2, name: 'b' },
  43. { id: 3, name: 'c' },
  44. ]
  45. expect(ArrayUtils.sortObjectsByProp(input, 'id')).toEqual(expected)
  46. })
  47. test('existing prop (reverse)', () => {
  48. const input = [
  49. { id: 2, name: 'b' },
  50. { id: 1, name: 'a' },
  51. { id: 3, name: 'c' },
  52. ]
  53. const expected = [
  54. { id: 3, name: 'c' },
  55. { id: 2, name: 'b' },
  56. { id: 1, name: 'a' },
  57. ]
  58. expect(ArrayUtils.sortObjectsByProp(input, 'id', true)).toEqual(expected)
  59. })
  60. })