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

Slice: Add none func (#13)

Returns true whether no elements of this slice match the provided predicate
func. Negated form of Every func
This commit is contained in:
donutloop
2022-01-05 12:38:14 +01:00
committed by GitHub
parent 4752725dd6
commit 4aef9d6d22
4 changed files with 36 additions and 0 deletions

View File

@@ -121,6 +121,28 @@ func Every(slice, function interface{}) bool {
return currentLength == sv.Len()
}
// None return true if all the values in the slice mismatch the criteria
// The function signature should be func(index int, value interface{}) bool .
func None(slice, function interface{}) bool {
sv := sliceValue(slice)
fn := functionValue(function)
elemType := sv.Type().Elem()
if checkSliceCallbackFuncSignature(fn, elemType, reflect.ValueOf(true).Type()) {
panic("function param should be of type func(int, " + elemType.String() + ")" + reflect.ValueOf(true).Type().String())
}
var currentLength int
for i := 0; i < sv.Len(); i++ {
flag := fn.Call([]reflect.Value{reflect.ValueOf(i), sv.Index(i)})[0]
if !flag.Bool() {
currentLength++
}
}
return currentLength == sv.Len()
}
// Some return true if any of the values in the list pass the predicate function.
// The function signature should be func(index int, value interface{}) bool .
func Some(slice, function interface{}) bool {

View File

@@ -108,6 +108,18 @@ func TestEvery(t *testing.T) {
}
}
func TestNone(t *testing.T) {
nums := []int{1, 2, 3, 5}
check := func(i, num int) bool {
return num%2 == 1
}
res := None(nums, check)
if res != false {
internal.LogFailedTestInfo(t, "Every", nums, false, res)
t.FailNow()
}
}
func TestSome(t *testing.T) {
nums := []int{1, 2, 3, 5}
isEven := func(i, num int) bool {