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