-
Notifications
You must be signed in to change notification settings - Fork 1
/
unique_test.go
74 lines (67 loc) · 1.32 KB
/
unique_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
package dogdirect
import (
"reflect"
"sort"
"testing"
)
var cases = []struct {
orig []string
want []string
}{
{nil, nil},
{[]string{"foo"}, []string{"foo"}},
{[]string{"foo", "bar"}, []string{"bar", "foo"}},
{[]string{"bar", "foo"}, []string{"bar", "foo"}},
{[]string{"foo", "foo"}, []string{"foo"}},
{[]string{"foo", "bar", "foo"}, []string{"bar", "foo"}},
{[]string{"foo", "foo", "bar"}, []string{"bar", "foo"}},
{[]string{"bar", "foo", "foo"}, []string{"bar", "foo"}},
{[]string{"foo", "foo", "foo"}, []string{"foo"}},
}
func TestUnique(t *testing.T) {
for i, c := range cases {
got := unique(c.orig)
sort.Strings(got)
if !reflect.DeepEqual(got, c.want) {
t.Errorf("Case %d: got %v want %v", i, got, c.want)
}
}
}
var fruitlist = []string{
"apricot",
"fig",
"avocado",
"apple",
"banana",
"lime",
"date",
"lemon",
}
// for comparison
func unique_map(s []string) []string {
seen := make(map[string]struct{}, len(s))
j := 0
for _, v := range s {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
s[j] = v
j++
}
return s[:j]
}
func BenchmarkUniqMap(b *testing.B) {
fruits := fruitlist
b.ReportAllocs()
for i := 0; i < b.N; i++ {
unique_map(fruits)
}
}
func BenchmarkUniqSort(b *testing.B) {
fruits := fruitlist
b.ReportAllocs()
for i := 0; i < b.N; i++ {
unique(fruits)
}
}