From 2a2dff841144350b581a28c7aa2fadc9f50a8505 Mon Sep 17 00:00:00 2001 From: Noah-Wagner Date: Fri, 13 Jan 2023 17:58:51 -1000 Subject: [PATCH] Add Count function to slices --- slices/slices.go | 11 +++++++++++ slices/slices_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/slices/slices.go b/slices/slices.go index cff0cd49e..5e9093278 100644 --- a/slices/slices.go +++ b/slices/slices.go @@ -134,6 +134,17 @@ func ContainsFunc[E any](s []E, f func(E) bool) bool { return IndexFunc(s, f) >= 0 } +// Count reports the number of items in s that are equal to v. +func Count[E comparable](s []E, v E) int { + count := 0 + for _, vs := range s { + if v == vs { + count += 1 + } + } + return count +} + // Insert inserts the values v... into s at index i, // returning the modified slice. // In the returned slice r, r[i] == v[0]. diff --git a/slices/slices_test.go b/slices/slices_test.go index 1d9ffd2f3..7245f0c17 100644 --- a/slices/slices_test.go +++ b/slices/slices_test.go @@ -377,6 +377,51 @@ func TestContainsFunc(t *testing.T) { } } +var countTests = []struct { + s []int + v int + want int +}{ + { + nil, + 0, + 0, + }, + { + []int{}, + 0, + 0, + }, + { + []int{1, 2, 3}, + 4, + 0, + }, + { + []int{1, 2, 3}, + 2, + 1, + }, + { + []int{1, 2, 2, 3}, + 2, + 2, + }, + { + []int{1, 2, 3, 2}, + 2, + 2, + }, +} + +func TestCount(t *testing.T) { + for _, test := range countTests { + if got := Count(test.s, test.v); got != test.want { + t.Errorf("Count(%v, %v) = %v, want %v", test.s, test.v, got, test.want) + } + } +} + var insertTests = []struct { s []int i int