tsortcall.nim 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. discard """
  2. outputsub: ""
  3. """
  4. import algorithm
  5. import unittest
  6. suite "test sort, sorted, and isSorted procs":
  7. proc foosort(ships: var seq[int]) = sort(ships, system.cmp[int])
  8. type
  9. User = object
  10. name: string
  11. age: int
  12. func newUser(name: string, age: int): User =
  13. result.name = name
  14. result.age = age
  15. proc compareUsers(x, y: User): int =
  16. if x.age == y.age: return 0
  17. if x.age < y.age: return -1
  18. return 1
  19. setup:
  20. var
  21. unSortedIntSeq = @[1, 4, 3, 5, -1]
  22. unSortedUserSeq = @[newUser("Andreas", 34), newUser("Alice", 12), newUser("Bob", 23)]
  23. let
  24. sortedIntSeq = @[-1, 1, 3, 4, 5]
  25. sortedUserSeq = @[newUser("Alice", 12), newUser("Bob", 23), newUser("Andreas", 34)]
  26. test "test the shortcut versions of sort, sorted, and isSorted":
  27. check(not unSortedIntSeq.isSorted)
  28. check sorted(unSortedIntSeq) == sortedIntSeq
  29. check sorted(unSortedIntSeq).isSorted
  30. unSortedIntSeq.sort()
  31. check unSortedIntSeq == sortedIntSeq
  32. check unSortedIntSeq.isSorted
  33. test "test the shortcut versions with descending sort order":
  34. check(not unSortedIntSeq.isSorted(SortOrder.Descending))
  35. check sorted(unSortedIntSeq, SortOrder.Descending) == reversed sortedIntSeq
  36. check sorted(unSortedIntSeq).isSorted(SortOrder.Ascending)
  37. unSortedIntSeq.sort(SortOrder.Descending)
  38. check unSortedIntSeq == reversed sortedIntSeq
  39. check unSortedIntSeq.isSorted(SortOrder.Descending)
  40. test "test the versions that accept a custom compareUsers function":
  41. check(not unSortedUserSeq.isSorted(compareUsers))
  42. check sorted(unSortedUserSeq, compareUsers) == sortedUserSeq
  43. check sorted(unSortedUserSeq, compareUsers).isSorted(compareUsers)
  44. unSortedUserSeq.sort(compareUsers)
  45. check unSortedUserSeq == sortedUserSeq
  46. check unSortedUserSeq.isSorted(compareUsers)
  47. test "test the long versions with descending sort order":
  48. check(not unSortedUserSeq.isSorted(compareUsers, SortOrder.Descending))
  49. check sorted(unSortedUserSeq, compareUsers, SortOrder.Descending) == reversed sortedUserSeq
  50. check sorted(unSortedUserSeq, compareUsers,
  51. SortOrder.Descending).isSorted(compareUsers, SortOrder.Descending)
  52. unSortedUserSeq.sort(compareUsers, SortOrder.Descending)
  53. check unSortedUserSeq == reversed sortedUserSeq
  54. check unSortedUserSeq.isSorted(compareUsers, SortOrder.Descending)