Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Count function to slices #55

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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