1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add EqualWithFunc function for slice

This commit is contained in:
dudaodong
2022-06-13 14:15:32 +08:00
parent 0cbb3dd97e
commit ef2d8e14b0
2 changed files with 29 additions and 0 deletions

View File

@@ -162,6 +162,22 @@ func Equal[T comparable](slice1, slice2 []T) bool {
return true
}
// EqualWithFunc checks if two slices are equal with comparator func
func EqualWithFunc[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) bool {
if len(slice1) != len(slice2) {
return false
}
for i, v1 := range slice1 {
v2 := slice2[i]
if !comparator(v1, v2) {
return false
}
}
return true
}
// Every return true if all of the values in the slice pass the predicate function.
func Every[T any](slice []T, predicate func(index int, item T) bool) bool {
if predicate == nil {

View File

@@ -79,6 +79,19 @@ func TestEqual(t *testing.T) {
assert.Equal(false, Equal(slice1, slice3))
}
func TestEqualWithFunc(t *testing.T) {
assert := internal.NewAssert(t, "TestEqualWithFunc")
slice1 := []int{1, 2, 3}
slice2 := []int{2, 4, 6}
isDouble := func(a, b int) bool {
return b == a*2
}
assert.Equal(true, EqualWithFunc(slice1, slice2, isDouble))
}
func TestEvery(t *testing.T) {
nums := []int{1, 2, 3, 5}
isEven := func(i, num int) bool {