From 0a8058956f325dbda60729db6844cb493ecbe887 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Sat, 3 Dec 2022 13:04:12 +0800 Subject: [PATCH] feat: add Count and CountBy function --- slice/slice.go | 17 +++++++++++++++-- slice/slice_test.go | 13 +++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/slice/slice.go b/slice/slice.go index 22b3089..a175387 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -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 { diff --git a/slice/slice_test.go b/slice/slice_test.go index 36c7459..be493ad 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -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) {