-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslices_distinct_test.go
96 lines (79 loc) · 1.78 KB
/
slices_distinct_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package generics
import (
"github.com/stretchr/testify/assert"
"hash/fnv"
"slices"
"strings"
"testing"
)
func TestSliceDistinct(t *testing.T) {
type ComplexKey struct {
A string
B string
}
keys := []ComplexKey{
{A: "b", B: "a"},
{A: "c", B: "c"},
{A: "b", B: "a"},
{A: "c", B: "b"},
{A: "c", B: "b"},
{A: "c", B: "b"},
{A: "c", B: "b"},
{A: "a", B: "a"},
{A: "a", B: "c"},
{A: "a", B: "c"},
{A: "a", B: "c"},
{A: "a", B: "b"},
}
t.Run("Distinct", func(t *testing.T) {
simpleKeys := Map(keys, func(index int, input ComplexKey) string { return input.A })
xx := Distinct(simpleKeys)
expected := []string{"a", "b", "c"}
assert.Equal(t, expected, xx)
})
t.Run("DistinctFunc", func(t *testing.T) {
xx := DistinctFunc(slices.Clone(keys), func(a, b ComplexKey) int {
if val := strings.Compare(a.A, b.A); val != 0 {
return val
}
return strings.Compare(a.B, b.B)
})
expected := []ComplexKey{
{A: "a", B: "a"},
{A: "a", B: "b"},
{A: "a", B: "c"},
{A: "b", B: "a"},
{A: "c", B: "b"},
{A: "c", B: "c"},
}
assert.Equal(t, expected, xx)
})
t.Run("DistinctStable", func(t *testing.T) {
xx := DistinctStable(slices.Clone(keys))
expected := []ComplexKey{
{A: "b", B: "a"},
{A: "c", B: "c"},
{A: "c", B: "b"},
{A: "a", B: "a"},
{A: "a", B: "c"},
{A: "a", B: "b"},
}
assert.Equal(t, expected, xx)
})
t.Run("DistinctStableFunc", func(t *testing.T) {
xx := DistinctStableFunc(slices.Clone(keys), func(val ComplexKey) uint64 {
h := fnv.New64a()
_, _ = h.Write([]byte(val.A + val.B))
return h.Sum64()
})
expected := []ComplexKey{
{A: "b", B: "a"},
{A: "c", B: "c"},
{A: "c", B: "b"},
{A: "a", B: "a"},
{A: "a", B: "c"},
{A: "a", B: "b"},
}
assert.Equal(t, expected, xx)
})
}