-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.go
More file actions
50 lines (42 loc) · 1.16 KB
/
array.go
File metadata and controls
50 lines (42 loc) · 1.16 KB
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
package arrayutil
import (
"fmt"
"reflect"
)
//Contains find whether array contains the search clause or not
func Contains(arr interface{}, clause interface{}) bool {
arrV := reflect.ValueOf(arr)
if arrV.Kind() != reflect.Slice {
return false
}
for i := 0; i < arrV.Len(); i++ {
entry := arrV.Index(i).Interface()
equal := reflect.DeepEqual(entry, clause)
if equal {
return true
}
}
return false
}
//Reduce an array of something into another thing
func Reduce(arr interface{}, initialValue interface{}, transform interface{}) (interface{}, error) {
arrV := reflect.ValueOf(arr)
kind := arrV.Kind()
if kind != reflect.Slice && kind != reflect.Array {
return nil, fmt.Errorf("Input value is not an array")
}
if transform == nil {
return nil, fmt.Errorf("Transform function cannot be nil")
}
tv := reflect.ValueOf(transform)
if tv.Kind() != reflect.Func {
return nil, fmt.Errorf("Transform argument must be a function")
}
accV := reflect.ValueOf(initialValue)
for i := 0; i < arrV.Len(); i++ {
entry := arrV.Index(i)
tfResults := tv.Call([]reflect.Value{accV, entry, reflect.ValueOf(i)})
accV = tfResults[0]
}
return accV.Interface(), nil
}