diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 85beea0..c1e2ac5 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -29,13 +29,13 @@ jobs: run: go install honnef.co/go/tools/cmd/staticcheck@latest - name: Install cover - run: go get -u golang.org/x/tools/cmd/cover + run: go install golang.org/x/tools/cmd/cover@latest - name: Install vet - run: go get -u github.com/mattn/goveralls + run: go install github.com/mattn/goveralls@latest - name: Install goveralls - run: go get -u github.com/mattn/goveralls + run: go install github.com/mattn/goveralls@latest - name: Staticcheck run: staticcheck -checks="all,-ST1000,-SA1019" github.com/msales/gox/... diff --git a/gofp/count.go b/gofp/count.go new file mode 100644 index 0000000..3e86ac5 --- /dev/null +++ b/gofp/count.go @@ -0,0 +1,10 @@ +package gofp + +func Count[T any](list []T, predicate func(T) bool) (res int64) { + for i := range list { + if predicate(list[i]) { + res++ + } + } + return +} diff --git a/gofp/count_test.go b/gofp/count_test.go new file mode 100644 index 0000000..33e3119 --- /dev/null +++ b/gofp/count_test.go @@ -0,0 +1,68 @@ +package gofp_test + +import ( + "testing" + + . "github.com/msales/gox/gofp" +) + +func TestCount(t *testing.T) { + tests := []struct { + name string + containsFn func() int64 + want int64 + }{ + { + name: "count 1", + containsFn: func() int64 { + slice := []int{1, 2, 3} + return Count(slice, func(i int) bool { + return i == 1 + }) + }, + want: 1, + }, + { + name: "count many", + containsFn: func() int64 { + slice := []int{1, 2, 3} + return Count(slice, func(i int) bool { + return i >= 2 + }) + }, + want: 2, + }, + { + name: "count zero", + containsFn: func() int64 { + slice := []int{1, 2, 3} + return Count(slice, func(i int) bool { + return i < 0 + }) + }, + want: 0, + }, + { + name: "count structs", + containsFn: func() int64 { + slice := []testStruct{ + {"1", 1}, + {"2", 2}, + {"3", 3}, + } + return Count(slice, func(ts testStruct) bool { + return ts.name == "1" || ts.name == "3" + }) + }, + want: 2, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.containsFn() + if tt.want != got { + t.Errorf("Got %+v, want %+v", got, tt.want) + } + }) + } +}