-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctor_test.go
69 lines (61 loc) · 1.55 KB
/
functor_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
package goslice_test
import (
"testing"
"github.com/makramkd/goslice"
"github.com/stretchr/testify/require"
)
func TestMap(t *testing.T) {
type s struct {
a int
b int32
}
coll := []s{{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 4}}
theAs := goslice.Map(coll, func(elem s) int {
return elem.a
})
require.ElementsMatch(t, []int{1, 2, 3}, theAs)
theBs := goslice.Map(coll, func(elem s) int32 {
return elem.b
})
require.ElementsMatch(t, []int32{2, 3, 4}, theBs)
}
func TestFilter(t *testing.T) {
type s struct {
a int
b int32
}
coll := []s{{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 4}}
evenAs := goslice.Filter(coll, func(elem s) bool {
return elem.a%2 == 0
})
require.ElementsMatch(t, []s{{a: 2, b: 3}}, evenAs)
}
func TestFilterNot(t *testing.T) {
type s struct {
a int
b int32
}
coll := []s{{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 4}}
oddAs := goslice.FilterNot(coll, func(elem s) bool {
return elem.a%2 == 0
})
require.ElementsMatch(t, []s{{a: 1, b: 2}, {a: 3, b: 4}}, oddAs)
}
func TestReduce(t *testing.T) {
// Simple case: accumulator and collection type are the same
coll := []int{1, 2, 3, 4, 5}
sum := goslice.Reduce(coll, func(a int, b int) int {
return a + b
}, 0)
require.Equal(t, 1+2+3+4+5, sum)
// general case: accumulator and collection type are different
type s struct {
a int
b int32
}
coll2 := []s{{a: 1, b: 2}, {a: 2, b: 3}, {a: 3, b: 4}}
abSum := goslice.Reduce(coll2, func(accum int64, elem s) int64 {
return accum + int64(elem.a) + int64(elem.b)
}, int64(0))
require.Equal(t, int64(1+2+2+3+3+4), abSum)
}