-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.go
80 lines (75 loc) · 1.49 KB
/
helper.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
package helper
import (
"go.mongodb.org/mongo-driver/bson/primitive"
"reflect"
"strconv"
)
func ConvertToFloat64(value any) float64 {
if value == nil {
return 0
}
typeOf := reflect.TypeOf(value).String()
switch typeOf {
case "float64":
return value.(float64)
case "float32":
return float64(value.(float32))
case "int":
return float64(value.(int))
case "int32":
return float64(value.(int32))
case "int64":
return float64(value.(int64))
case "string":
f, _ := strconv.ParseFloat(value.(string), 64)
return f
case "primitive.Decimal128":
dec := value.(primitive.Decimal128)
str := dec.String()
f, _ := strconv.ParseFloat(str, 64)
return f
default:
return 0
}
}
func ConvertToInt(value any) int {
if value == nil {
return 0
}
typeOf := reflect.TypeOf(value).String()
switch typeOf {
case "float64":
return int(value.(float64))
case "float32":
return int(value.(float32))
case "int":
return value.(int)
case "int32":
return int(value.(int32))
case "int64":
return int(value.(int64))
case "string":
i, _ := strconv.Atoi(value.(string))
return i
case "primitive.Decimal128":
dec := value.(primitive.Decimal128)
str := dec.String()
i, _ := strconv.Atoi(str)
return i
default:
return 0
}
}
func Contains[T comparable](elems []T, v T, fn func(value T, element T) bool) bool {
if fn == nil {
fn = func(value T, element T) bool {
return value == element
}
}
for _, s := range elems {
if fn(v, s) {
return true
}
}
return false
}