...
1 package funk
2
3 import (
4 "reflect"
5 )
6
7
8 func predicatesImpl(value interface{}, wantedAnswer bool, predicates interface{}) bool {
9 if !IsCollection(predicates) {
10 panic("Predicates parameter must be an iteratee")
11 }
12
13 predicatesValue := reflect.ValueOf(predicates)
14 inputValue := reflect.ValueOf(value)
15
16 for i := 0; i < predicatesValue.Len(); i++ {
17 funcValue := predicatesValue.Index(i)
18 if !IsFunction(funcValue.Interface()) {
19 panic("Got non function as predicate")
20 }
21
22 funcType := funcValue.Type()
23 if !IsPredicate(funcValue.Interface()) {
24 panic("Predicate function must have 1 parameter and must return boolean")
25 }
26
27 if !inputValue.Type().ConvertibleTo(funcType.In(0)) {
28 panic("Given value is not compatible with type of parameter for the predicate.")
29 }
30 if result := funcValue.Call([]reflect.Value{inputValue}); wantedAnswer == result[0].Bool() {
31 return wantedAnswer
32 }
33 }
34
35 return !wantedAnswer
36 }
37
38
39
40 func AnyPredicates(value interface{}, predicates interface{}) bool {
41 return predicatesImpl(value, true, predicates)
42 }
43
44
45 func AllPredicates(value interface{}, predicates interface{}) bool {
46 return predicatesImpl(value, false, predicates)
47 }
48
View as plain text