-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathmap_test.go
69 lines (63 loc) · 1.21 KB
/
map_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 underscore
import (
"reflect"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
)
func Test_Map(t *testing.T) {
t.Run("default", func(t *testing.T) {
src := []string{"11", "12", "13"}
var res []int
Chain(src).Map(func(s string, _ int) int {
n, _ := strconv.Atoi(s)
return n
}).Value(&res)
assert.EqualValues(
t,
res,
[]int{11, 12, 13},
)
})
t.Run("元素是指针", func(t *testing.T) {
src := []string{"11", "12", "13"}
var res []*string
Chain(src).Map(func(r string, _ int) *string {
return &r
}).Value(&res)
assert.EqualValues(
t,
res,
[]*string{&src[0], &src[1], &src[2]},
)
})
t.Run("结果为reflect.Value", func(t *testing.T) {
resValue := reflect.New(
reflect.SliceOf(
reflect.TypeOf(1),
),
)
Chain([]string{"a", "b"}).Map(func(_ string, i int) int {
return i
}).Value(resValue)
assert.EqualValues(
t,
resValue.Elem().Interface(),
[]int{0, 1},
)
})
}
func Test_MapBy(t *testing.T) {
src := []testModel{
{ID: 1, Name: "one"},
{ID: 2, Name: "two"},
{ID: 3, Name: "three"},
}
var res []string
Chain(src).MapBy("name").Value(&res)
assert.EqualValues(
t,
res,
[]string{"one", "two", "three"},
)
}