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

feat: add EqualWith function for slice

This commit is contained in:
dudaodong
2022-06-17 15:47:36 +08:00
parent a2541dac03
commit 433eb63b86
2 changed files with 33 additions and 0 deletions

View File

@@ -225,6 +225,26 @@ func Equal(slice1, slice2 interface{}) bool {
return true
}
// EqualWith checks if two slices are equal with comparator func
func EqualWith(slice1, slice2 interface{}, comparator interface{}) bool {
sv1 := sliceValue(slice1)
sv2 := sliceValue(slice2)
fn := functionValue(comparator)
// elemType1 := sv1.Type().Elem()
// elemType2 := sv2.Type().Elem()
// todo: check fn signature: func(a elemType1.Kind(), b elemType2.Kind()) bool
for i := 0; i < sv1.Len(); i++ {
flag := fn.Call([]reflect.Value{sv1.Index(i), sv2.Index(i)})[0]
if !flag.Bool() {
return false
}
}
return true
}
// Every return true if all of the values in the slice pass the predicate function.
// The function signature should be func(index int, value interface{}) bool .
func Every(slice, function interface{}) bool {

View File

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