Skip to content

Commit eb7fca5

Browse files
author
yangyile
committed
继续添加逻辑
1 parent 58015bb commit eb7fca5

File tree

4 files changed

+40
-0
lines changed

4 files changed

+40
-0
lines changed

internal/utils/zero.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package utils
2+
3+
func Zero[T any]() (x T) {
4+
return x
5+
}

internal/utils/zero_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package utils_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/go-zwbc/slicezh/internal/utils"
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func TestZero(t *testing.T) {
11+
require.Equal(t, 0, utils.Zero[int]())
12+
require.Equal(t, "", utils.Zero[string]())
13+
require.Equal(t, 0.0, utils.Zero[float64]())
14+
require.Equal(t, rune(0), utils.Zero[rune]())
15+
}

slice.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package slicezh
33
import (
44
"math/rand/v2"
55
"slices"
6+
7+
"github.com/go-zwbc/slicezh/internal/utils"
68
)
79

810
func Do过滤[T any](a []T, condition func(value T) bool) []T {
@@ -15,6 +17,15 @@ func Do过滤[T any](a []T, condition func(value T) bool) []T {
1517
return results
1618
}
1719

20+
func Get首个满足条件的[T any](a []T, condition func(value T) bool) (T, bool) {
21+
for _, one := range a {
22+
if condition(one) {
23+
return one, true
24+
}
25+
}
26+
return utils.Zero[T](), false
27+
}
28+
1829
func Do翻转[T any](a []T) {
1930
slices.Reverse(a)
2031
}

slice_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ func TestDo过滤(t *testing.T) {
1515
require.Equal(t, []int{2, 4}, results)
1616
}
1717

18+
func TestGet首个满足条件的(t *testing.T) {
19+
one, ok := slicezh.Get首个满足条件的([]int{1, 2, 3, 4, 5}, func(value int) bool {
20+
return value%2 == 0
21+
})
22+
require.True(t, ok)
23+
t.Log(one)
24+
require.Equal(t, 2, one)
25+
}
26+
1827
func TestDo翻转(t *testing.T) {
1928
a := []string{"a", "b", "c"}
2029
slicezh.Do翻转(a)

0 commit comments

Comments
 (0)