v / vlib / builtin
Raw file | 84 loc (72 sloc) | 1.56 KB | Latest commit hash 017ace6ea
1const (
2 unsorted = [2, 30, 10, 20, 1]
3 sorted_asc = [1, 2, 10, 20, 30]
4 sorted_desc = [30, 20, 10, 2, 1]
5)
6
7fn test_sorting_simple() {
8 mut a := unsorted.clone()
9 a.sort()
10 println(' a: ${a}')
11 assert a == sorted_asc
12}
13
14fn test_sorting_with_condition_expression() {
15 mut a := unsorted.clone()
16 a.sort(a > b)
17 println(' a: ${a}')
18 assert a == sorted_desc
19}
20
21fn test_sorting_primitives_with_condition_expression() {
22 mut x := ['9', '87', '3210', '654']
23 x.sort(a.len < b.len)
24 assert x == ['9', '87', '654', '3210']
25}
26
27// fn get_score(word string) int {
28// mut total := 0
29// for letter in word {
30// total += int(letter) - 97
31// }
32// return total
33// }
34
35// fn test_sorting_with_fn_call_in_condition_expression() {
36// mut words := ['aaaa', 'a', 'b', 'foo', 'bar']
37// words.sort(get_score(a) < get_score(b))
38// }
39
40fn mysort(mut a []int) {
41 a.sort()
42}
43
44fn test_sorting_by_passing_a_mut_array_to_a_function() {
45 mut a := unsorted.clone()
46 mysort(mut a)
47 println(' a: ${a}')
48 assert a == sorted_asc
49}
50
51/*
52fn test_sorting_by_passing_an_anonymous_sorting_function() {
53 mut a := unsorted
54 a.sort(fn(a &int, b &int) int { return *b - *a })
55 println(' a: $a')
56 assert a == sort_desc
57}
58*/
59fn test_sorting_u64s() {
60 mut a := [u64(3), 2, 1, 9, 0, 8]
61 a.sort()
62 println(' a: ${a}')
63 assert a == [u64(0), 1, 2, 3, 8, 9]
64 a.sort(a > b)
65 println(' a: ${a}')
66 assert a == [u64(9), 8, 3, 2, 1, 0]
67}
68
69struct User {
70 age int
71 name string
72}
73
74fn g(mut users []User) {
75 users.sort(a.name > b.name)
76}
77
78fn f(mut users []User) {
79 users.sort(a.name < b.name)
80}
81
82fn z(mut users []User) {
83 users.sort(a.name < b.name)
84}