Skip to content
Merged
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
9 changes: 9 additions & 0 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@ func SliceContains[T any](slice []T, filter func(t T) bool) bool {
return false
}

func AllElements[T any](slice []T, filter func(t T) bool) bool {
for _, item := range slice {
if !filter(item) {
return false
}
}
return true
}

func SliceContainsElement[T comparable](slice []T, element T) bool {
return SliceContains(slice, func(t T) bool {
return t == element
Expand Down
63 changes: 63 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,69 @@ func TestSliceContains(t *testing.T) {
})
}

func TestSliceEvery(t *testing.T) {
t.Parallel()

t.Run("all elements match", func(t *testing.T) {
t.Parallel()

slice := []int{1, 1, 1, 1}
returns := generic.AllElements(slice, func(i int) bool {
return i == 1
})

t.Log("Should return true when all elements match condition")
assert.True(t, returns)
})

t.Run("returns false if not all elements match", func(t *testing.T) {
t.Parallel()

slice := []int{1, 2, 1, 1}
returns := generic.AllElements(slice, func(i int) bool {
return i == 1
})

t.Log("Should return false when not all elements match condition")
assert.False(t, returns)
})

t.Run("checks complex condition", func(t *testing.T) {
t.Parallel()

type User struct {
Name string
Admin bool
}

users := []User{
{"Alice", false},
{"Bob", false},
{"Charlie", false},
}

returns := generic.AllElements(users, func(u User) bool {
return !u.Admin
})

t.Log("Should return true when all users are not admins")
assert.True(t, returns)

users = []User{
{"Alice", false},
{"Bob", true},
{"Charlie", false},
}

returns = generic.AllElements(users, func(u User) bool {
return u.Admin
})

t.Log("Should return false when not all users are admins")
assert.False(t, returns)
})
}

func TestSliceContainsElement(t *testing.T) {
t.Parallel()

Expand Down
Loading