mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add Count and CountBy function
This commit is contained in:
@@ -215,8 +215,21 @@ func Filter[T any](slice []T, predicate func(index int, item T) bool) []T {
|
||||
return result
|
||||
}
|
||||
|
||||
// Count iterates over elements of slice, returns a count of all matched elements
|
||||
func Count[T any](slice []T, predicate func(index int, item T) bool) int {
|
||||
// Count returns the number of occurrences of the given item in the slice
|
||||
func Count[T comparable](slice []T, item T) int {
|
||||
count := 0
|
||||
|
||||
for _, v := range slice {
|
||||
if item == v {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
// CountBy iterates over elements of slice with predicate function, returns the number of all matched elements
|
||||
func CountBy[T any](slice []T, predicate func(index int, item T) bool) int {
|
||||
count := 0
|
||||
|
||||
for i, v := range slice {
|
||||
|
||||
@@ -193,13 +193,22 @@ func TestGroupWith(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCount(t *testing.T) {
|
||||
numbers := []int{1, 2, 3, 3, 5, 6}
|
||||
|
||||
assert := internal.NewAssert(t, "TestCountBy")
|
||||
|
||||
assert.Equal(1, Count(numbers, 1))
|
||||
assert.Equal(2, Count(numbers, 3))
|
||||
}
|
||||
|
||||
func TestCountBy(t *testing.T) {
|
||||
nums := []int{1, 2, 3, 4, 5, 6}
|
||||
evenFunc := func(i, num int) bool {
|
||||
return (num % 2) == 0
|
||||
}
|
||||
|
||||
assert := internal.NewAssert(t, "TestCount")
|
||||
assert.Equal(3, Count(nums, evenFunc))
|
||||
assert := internal.NewAssert(t, "TestCountBy")
|
||||
assert.Equal(3, CountBy(nums, evenFunc))
|
||||
}
|
||||
|
||||
func TestFind(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user