diff --git a/README.md b/README.md index cb8dc57..6423bf7 100644 --- a/README.md +++ b/README.md @@ -420,6 +420,7 @@ func Union(slices ...interface{}) interface{} //Union creates a slice of unique func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //update the slice element at index. func Without(slice interface{}, values ...interface{}) interface{} //creates a slice excluding all given values func GroupBy(slice, function interface{}) (interface{}, interface{}) // groups slice into two categories +func Count(slice, function interface{}) int // Count iterates over elements of slice, returns a count of all matched elements ``` #### 10. strutil is for processing string diff --git a/README_zh-CN.md b/README_zh-CN.md index 39f0207..25990f5 100644 --- a/README_zh-CN.md +++ b/README_zh-CN.md @@ -421,6 +421,7 @@ func Union(slices ...interface{}) interface{} //slice并集, 去重 func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) //在切片中index位置更新value func Without(slice interface{}, values ...interface{}) interface{} //slice去除values func GroupBy(slice, function interface{}) (interface{}, interface{}) //根据函数function的逻辑分slice为两组slice +func Count(slice, function interface{}) int ``` #### 10. strutil字符串处理包 diff --git a/slice/slice.go b/slice/slice.go index 9152d72..8df6748 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -187,6 +187,28 @@ func Filter(slice, function interface{}) interface{} { return res.Interface() } +// Count iterates over elements of slice, returns a count of all matched elements +// The function signature should be func(index int, value interface{}) bool . +func Count(slice, function interface{}) int { + sv := sliceValue(slice) + fn := functionValue(function) + + elemType := sv.Type().Elem() + if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) { + panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String()) + } + + var counter int + for i := 0; i < sv.Len(); i++ { + flag := fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})[0] + if flag.Bool() { + counter++ + } + } + + return counter +} + // GroupBy iterate over elements of the slice, each element will be group by criteria, returns two slices // The function signature should be func(index int, value interface{}) bool . func GroupBy(slice, function interface{}) (interface{}, interface{}) { diff --git a/slice/slice_test.go b/slice/slice_test.go index 2e25613..db28b10 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -197,6 +197,19 @@ func TestGroupBy(t *testing.T) { } } +func TestCount(t *testing.T) { + nums := []int{1, 2, 3, 4, 5, 6} + evenFunc := func(i, num int) bool { + return (num % 2) == 0 + } + c := Count(nums, evenFunc) + + if c != 3 { + internal.LogFailedTestInfo(t, "Count", nums, 3, c) + t.FailNow() + } +} + func TestFind(t *testing.T) { nums := []int{1, 2, 3, 4, 5} even := func(i, num int) bool {