Skip to content

Commit

Permalink
Add Count function to slices
Browse files Browse the repository at this point in the history
  • Loading branch information
Noah-Wagner committed Jan 14, 2023
1 parent f9f960f commit 2a2dff8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
11 changes: 11 additions & 0 deletions slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -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].
Expand Down
45 changes: 45 additions & 0 deletions slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 2a2dff8

Please sign in to comment.