| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package containers |
| 8 |
|
| 9 |
import ( |
| 10 |
"cmp" |
| 11 |
"fmt" |
| 12 |
"strings" |
| 13 |
"testing" |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
type ContainerTest[T any] struct { |
| 18 |
values []T |
| 19 |
} |
| 20 |
|
| 21 |
func (container ContainerTest[T]) Empty() bool { |
| 22 |
return len(container.values) == 0 |
| 23 |
} |
| 24 |
|
| 25 |
func (container ContainerTest[T]) Size() int { |
| 26 |
return len(container.values) |
| 27 |
} |
| 28 |
|
| 29 |
func (container ContainerTest[T]) Clear() { |
| 30 |
container.values = []T{} |
| 31 |
} |
| 32 |
|
| 33 |
func (container ContainerTest[T]) Values() []T { |
| 34 |
return container.values |
| 35 |
} |
| 36 |
|
| 37 |
func (container ContainerTest[T]) String() string { |
| 38 |
str := "ContainerTest\n" |
| 39 |
var values []string |
| 40 |
for _, value := range container.values { |
| 41 |
values = append(values, fmt.Sprintf("%v", value)) |
| 42 |
} |
| 43 |
str += strings.Join(values, ", ") |
| 44 |
return str |
| 45 |
} |
| 46 |
|
| 47 |
func TestGetSortedValuesInts(t *testing.T) { |
| 48 |
container := ContainerTest[int]{} |
| 49 |
GetSortedValues(container) |
| 50 |
container.values = []int{5, 1, 3, 2, 4} |
| 51 |
values := GetSortedValues(container) |
| 52 |
for i := 1; i < container.Size(); i++ { |
| 53 |
if values[i-1] > values[i] { |
| 54 |
t.Errorf("Not sorted!") |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
type NotInt struct { |
| 60 |
i int |
| 61 |
} |
| 62 |
|
| 63 |
func TestGetSortedValuesNotInts(t *testing.T) { |
| 64 |
container := ContainerTest[NotInt]{} |
| 65 |
GetSortedValuesFunc(container, func(x, y NotInt) int { |
| 66 |
return cmp.Compare(x.i, y.i) |
| 67 |
}) |
| 68 |
container.values = []NotInt{{5}, {1}, {3}, {2}, {4}} |
| 69 |
values := GetSortedValuesFunc(container, func(x, y NotInt) int { |
| 70 |
return cmp.Compare(x.i, y.i) |
| 71 |
}) |
| 72 |
for i := 1; i < container.Size(); i++ { |
| 73 |
if values[i-1].i > values[i].i { |
| 74 |
t.Errorf("Not sorted!") |
| 75 |
} |
| 76 |
} |
| 77 |
} |