tsortcall.nim 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  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 = default(User)
  14. result.name = name
  15. result.age = age
  16. proc compareUsers(x, y: User): int =
  17. if x.age == y.age: return 0
  18. if x.age < y.age: return -1
  19. return 1
  20. setup:
  21. var
  22. unSortedIntSeq = @[1, 4, 3, 5, -1]
  23. unSortedUserSeq = @[newUser("Andreas", 34), newUser("Alice", 12), newUser("Bob", 23)]
  24. let
  25. sortedIntSeq = @[-1, 1, 3, 4, 5]
  26. sortedUserSeq = @[newUser("Alice", 12), newUser("Bob", 23), newUser("Andreas", 34)]
  27. test "test the shortcut versions of sort, sorted, and isSorted":
  28. check(not unSortedIntSeq.isSorted)
  29. check sorted(unSortedIntSeq) == sortedIntSeq
  30. check sorted(unSortedIntSeq).isSorted
  31. unSortedIntSeq.sort()
  32. check unSortedIntSeq == sortedIntSeq
  33. check unSortedIntSeq.isSorted
  34. test "test the shortcut versions with descending sort order":
  35. check(not unSortedIntSeq.isSorted(SortOrder.Descending))
  36. check sorted(unSortedIntSeq, SortOrder.Descending) == reversed sortedIntSeq
  37. check sorted(unSortedIntSeq).isSorted(SortOrder.Ascending)
  38. unSortedIntSeq.sort(SortOrder.Descending)
  39. check unSortedIntSeq == reversed sortedIntSeq
  40. check unSortedIntSeq.isSorted(SortOrder.Descending)
  41. test "test the versions that accept a custom compareUsers function":
  42. check(not unSortedUserSeq.isSorted(compareUsers))
  43. check sorted(unSortedUserSeq, compareUsers) == sortedUserSeq
  44. check sorted(unSortedUserSeq, compareUsers).isSorted(compareUsers)
  45. unSortedUserSeq.sort(compareUsers)
  46. check unSortedUserSeq == sortedUserSeq
  47. check unSortedUserSeq.isSorted(compareUsers)
  48. test "test the long versions with descending sort order":
  49. check(not unSortedUserSeq.isSorted(compareUsers, SortOrder.Descending))
  50. check sorted(unSortedUserSeq, compareUsers, SortOrder.Descending) == reversed sortedUserSeq
  51. check sorted(unSortedUserSeq, compareUsers,
  52. SortOrder.Descending).isSorted(compareUsers, SortOrder.Descending)
  53. unSortedUserSeq.sort(compareUsers, SortOrder.Descending)
  54. check unSortedUserSeq == reversed sortedUserSeq
  55. check unSortedUserSeq.isSorted(compareUsers, SortOrder.Descending)