-
Notifications
You must be signed in to change notification settings - Fork 4
/
generic.go
100 lines (84 loc) · 1.95 KB
/
generic.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package utils
import "encoding/json"
// Contains tells whether slice A contains x.
func Contains[T comparable](a []T, x T) bool {
for _, n := range a {
if x == n {
return true
}
}
return false
}
// Difference get discrepancies between 2 slices
func Difference[T comparable](slice1 []T, slice2 []T) []T {
var diff []T
// Loop two times, first to find slice1 strings not in slice2,
// second loop to find slice2 strings not in slice1
for i := 0; i < 2; i++ {
for _, s1 := range slice1 {
found := false
for _, s2 := range slice2 {
if s1 == s2 {
found = true
break
}
}
// String not found. We add it to return slice
if !found {
diff = append(diff, s1)
}
}
// Swap the slices, only if it was the first loop
if i == 0 {
slice1, slice2 = slice2, slice1
}
}
return diff
}
// Unique returns unique value in as slice
func Unique[T comparable](elements []T) (result []T) {
encountered := map[T]bool{}
for idx := range elements {
if _, ok := encountered[elements[idx]]; ok {
continue
}
encountered[elements[idx]] = true
result = append(result, elements[idx])
}
return result
}
// InterfaceBytesToType will transform cached value that get from the redis to any types
func InterfaceBytesToType[T any](i interface{}) (out T) {
if i == nil {
return
}
bt := i.([]byte)
_ = json.Unmarshal(bt, &out)
return
}
// ValueOrDefault use the given value or use default value if the value = empty value
func ValueOrDefault[T comparable](value, defaultValue T) T {
var emptyValue T
if value == emptyValue {
return defaultValue
}
return value
}
// DeleteByValue use for delete value in slice
func DeleteByValue[T comparable](a []T, x T) []T {
var newValue []T
for _, n := range a {
if x != n {
newValue = append(newValue, n)
}
}
return newValue
}
// ValueOfPointer return value of pointer T
func ValueOfPointer[T comparable](i *T) T {
var emptyValue T
if i == nil {
return emptyValue
}
return *i
}