-
Notifications
You must be signed in to change notification settings - Fork 3
/
foreach.go
82 lines (64 loc) · 1.97 KB
/
foreach.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package reflectutils
import (
"fmt"
"reflect"
)
func ForEach(arr interface{}, predicate interface{}) {
var (
funcValue = reflect.ValueOf(predicate)
arrValue = reflect.ValueOf(arr)
arrType = arrValue.Type()
arrKind = arrType.Kind()
funcType = funcValue.Type()
)
if IsNil(arr) {
return
}
if !(arrKind == reflect.Array || arrKind == reflect.Slice || arrKind == reflect.Map) {
panic("First parameter must be an iteratee")
}
if arrKind == reflect.Slice || arrKind == reflect.Array {
if !isFunction(predicate, 1, 0) {
panic("Second argument must be a function with one parameter")
}
arrElemType := arrValue.Type().Elem()
// Checking whether element type is convertible to function's first argument's type.
if !arrElemType.ConvertibleTo(funcType.In(0)) {
panic("Map function's argument is not compatible with type of array.")
}
for i := 0; i < arrValue.Len(); i++ {
funcValue.Call([]reflect.Value{arrValue.Index(i)})
}
return
}
if arrKind == reflect.Map {
if !isFunction(predicate, 2, 0) {
panic("Second argument must be a function with two parameters")
}
// Type checking for Map<key, value> = (key, value)
keyType := arrType.Key()
valueType := arrType.Elem()
if !keyType.ConvertibleTo(funcType.In(0)) {
panic(fmt.Sprintf("function first argument is not compatible with %s", keyType.String()))
}
if !valueType.ConvertibleTo(funcType.In(1)) {
panic(fmt.Sprintf("function second argument is not compatible with %s", valueType.String()))
}
for _, key := range arrValue.MapKeys() {
funcValue.Call([]reflect.Value{key, arrValue.MapIndex(key)})
}
return
}
}
// isFunction returns if the argument is a function.
func isFunction(in interface{}, num ...int) bool {
funcType := reflect.TypeOf(in)
result := funcType != nil && funcType.Kind() == reflect.Func
if len(num) >= 1 {
result = result && funcType.NumIn() == num[0]
}
if len(num) == 2 {
result = result && funcType.NumOut() == num[1]
}
return result
}