arrayUtils.test.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. })