-
Notifications
You must be signed in to change notification settings - Fork 6
/
find_test.go
119 lines (97 loc) · 2.5 KB
/
find_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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package godash_test
import (
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/thecasualcoder/godash"
)
func TestFind(t *testing.T) {
t.Run("should filter elements that fail predicate", func(t *testing.T) {
input := []int{1, 2, 3, 4, 5, 6, 7, 8}
var output int
err := godash.Find(input, &output, func(a int) bool {
return a == 1 // starts with
})
expected := 1
assert.NoError(t, err)
assert.Equal(t, expected, output)
})
t.Run("should struct types", func(t *testing.T) {
type person struct {
age int
}
input := []person{
{30},
{20},
{40},
{10},
}
var output person
err := godash.Find(input, &output, func(p person) bool {
return p.age > 20
})
expected := person{30}
assert.NoError(t, err)
assert.Equal(t, expected, output)
})
t.Run("should validate predicate's arg", func(t *testing.T) {
input := []int{1, 2, 3, 4, 5, 6, 7, 8}
var output int
err := godash.Find(input, &output, func(a string) bool {
return a == ""
})
assert.EqualError(t, err, "predicate function's first argument has to be the type (int) instead of (string)")
})
t.Run("should validate predicate's return type", func(t *testing.T) {
input := []int{1, 2, 3, 4, 5, 6, 7, 8}
var output int
{
err := godash.Find(input, &output, func(a int) int {
return a
})
assert.EqualError(t, err, "predicate function should return only a (boolean) and not a (int)")
}
{
err := godash.Find(input, &output, func(int) (int, bool) {
return 1, true
})
assert.EqualError(t, err, "predicate function should return only one return value - a boolean")
}
})
t.Run("should validate output's type", func(t *testing.T) {
input := []int{1, 2, 3, 4, 5, 6, 7, 8}
var output string
err := godash.Find(input, &output, func(a int) bool {
return a == 0
})
assert.EqualError(t, err, "input slice (int) and output (string) should be of the same Type")
})
t.Run("should return error if element not found", func(t *testing.T) {
in := []int{1, 2, 3}
{
var out int
err := godash.Find(in, &out, func(x int) bool { return x == 4 })
assert.EqualError(t, err, "element not found")
}
{
var out int
err := godash.Find(in, &out, func(x int) bool { return x == 1 })
assert.NoError(t, err)
}
})
}
func ExampleFind() {
input := []string{
"rhythm",
"of",
"life",
}
var output string
_ = godash.Find(input, &output, func(in string) bool {
return strings.HasPrefix(in, "r")
})
fmt.Println(output)
// Output:
// rhythm
}