-
Notifications
You must be signed in to change notification settings - Fork 4
/
generic.go
339 lines (281 loc) · 8.05 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package utils
import (
"math"
"reflect"
"regexp"
"strings"
)
var (
regexpAnyToSnakeCase = regexp.MustCompile("[!@#%^':;&|\\[\\]*=+><()\\s]+|([^\\s_$-])([A-Z][a-z])")
regexpSnakeToCamelCase = regexp.MustCompile("_[a-z-\\d]")
)
// KeysInMapAndNotBlank checks presence of non blank values for keys in map
// - first arg must be map
// - fallowing arguments are map keys you want to check
func KeysInMapAndNotBlank(mapObject interface{}, keys ...interface{}) bool {
switch typedMapObject := mapObject.(type) {
case map[string]interface{}:
for _, key := range keys {
if key2, ok := key.(string); ok {
if mapValue, present := typedMapObject[key2]; present {
if isBlank := CheckIsBlank(mapValue); isBlank {
return false
}
} else {
return false
}
}
}
case map[int]interface{}:
for _, key := range keys {
if key, ok := key.(int); ok {
if mapValue, present := typedMapObject[key]; present {
if isBlank := CheckIsBlank(mapValue); isBlank {
return false
}
} else {
return false
}
}
}
}
return true
}
// GetFirstMapValue returns map key value or nil if not found, will be returned first found key value
func GetFirstMapValue(mapObject interface{}, keys ...string) interface{} {
switch typedMapObject := mapObject.(type) {
case map[string]interface{}:
for _, key := range keys {
if value, present := typedMapObject[key]; present {
return value
}
}
case map[string]string:
for _, key := range keys {
if value, present := typedMapObject[key]; present {
return value
}
}
}
return nil
}
// IsInArray searches for item in array/slice, returns true if found
func IsInArray(searchValue interface{}, arrayObject interface{}) bool {
switch typedObject := arrayObject.(type) {
case []string:
searchValue, ok := searchValue.(string)
if !ok {
return false
}
for _, value := range typedObject {
if value == searchValue {
return true
}
}
case []interface{}:
for _, value := range typedObject {
if value == searchValue {
return true
}
}
}
return false
}
// IsAmongStr searches for presence of 1-st arg string option among provided options since 2-nd argument
func IsAmongStr(option string, searchOptions ...string) bool {
for _, listOption := range searchOptions {
if option == listOption {
return true
}
}
return false
}
// IsInListStr searches for a string in []string slice
func IsInListStr(searchItem string, searchList []string) bool {
for _, listItem := range searchList {
if listItem == searchItem {
return true
}
}
return false
}
// StrKeysInMap checks presence of string keys in map
func StrKeysInMap(mapObject interface{}, keys ...string) bool {
switch typedMap := mapObject.(type) {
case map[string]interface{}: //, map[string]string:
for _, key := range keys {
if _, present := typedMap[key]; !present {
return false
}
}
}
return true
}
// Explode returns trimmed []string array of [separators] delimited values
func Explode(value string, separators string) []string {
var result []string
splitResult := strings.Split(value, separators)
for _, arrayValue := range splitResult {
arrayValue = strings.TrimSpace(arrayValue)
if arrayValue != "" {
result = append(result, arrayValue)
}
}
return result
}
// Round rounds value to given precision (roundOn=0.5 usual cases)
func Round(value float64, round float64, precision int) float64 {
negative := false
if negative = math.Signbit(value); negative {
value = -value
}
precisionPart := math.Pow(10, float64(precision))
poweredValue := precisionPart * value
_, roundingPart := math.Modf(poweredValue)
var roundResult float64
if roundingPart >= round {
roundResult = math.Ceil(poweredValue)
} else {
roundResult = math.Floor(poweredValue)
}
if negative {
roundResult = -roundResult
}
return roundResult / precisionPart
}
// RoundPrice normalize price after calculations, so it rounds it to money precision
func RoundPrice(price float64) float64 {
return Round(price, 0.5, 2)
}
// SplitQuotedStringBy splits string by character(s) unless it in quotes
func SplitQuotedStringBy(text string, separators ...rune) []string {
lastQuote := rune(0)
escapeFlag := false
operator := func(currentChar rune) bool {
isSeparatorChar := false
for _, separator := range separators {
if currentChar == separator {
isSeparatorChar = true
break
}
}
switch {
case currentChar == '\\':
escapeFlag = true
case !escapeFlag && lastQuote == currentChar:
lastQuote = rune(0)
return false
case lastQuote == rune(0) && (currentChar == '"' || currentChar == '\'' || currentChar == '`'):
lastQuote = currentChar
return false
case lastQuote == rune(0) && isSeparatorChar:
return true
}
escapeFlag = false
return false
}
return strings.FieldsFunc(text, operator)
}
// MatchMapAValuesToMapB compares key values of mapA to same key value of mapB, returns true
// if all keys in mapA present and matches keys in mapB
func MatchMapAValuesToMapB(mapA map[string]interface{}, mapB map[string]interface{}) bool {
if mapA == nil || mapB == nil {
if mapA == nil && mapB == nil {
return true
}
return false
}
for key, valueA := range mapA {
if valueB, present := mapB[key]; present {
switch valueA.(type) {
case []interface{}:
typedValueA, okA := valueA.([]interface{})
typedValueB, okB := valueB.([]interface{})
if okA && okB {
for _, itemA := range typedValueA {
found := false
for _, itemB := range typedValueB {
if itemA == itemB {
found = true
break
}
}
if !found {
return false
}
}
return true
}
return false
case map[string]interface{}:
typedValueA, okA := valueA.(map[string]interface{})
typedValueB, okB := valueB.(map[string]interface{})
if okA && okB {
return MatchMapAValuesToMapB(typedValueA, typedValueB)
}
return false
default:
if valueA != valueB {
return false
}
}
} else {
return false
}
}
return true
}
// EscapeRegexSpecials returns regular expression special characters escaped value
func EscapeRegexSpecials(value string) string {
specials := []string{"\\", "-", "[", "]", "/", "{", "}", "(", ")", "*", "+", "?", ".", "^", "$", "|"}
for _, special := range specials {
value = strings.Replace(value, special, "\\"+special, -1)
}
return value
}
// ValidEmailAddress takes an email address as string compares it agasint a regular expression
// - returns true if email address is in a valid format
// - returns false if email address is not in a valid format
func ValidEmailAddress(email string) bool {
re := regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,4}$`)
return re.MatchString(email)
}
// Clone will create a replica for a given object
func Clone(subject interface{}) interface{} {
result := subject
subjectValue := reflect.ValueOf(subject)
subjectKind := subjectValue.Kind()
if subjectKind == reflect.Array || subjectKind == reflect.Slice {
len := subjectValue.Len()
newValue := reflect.MakeSlice(subjectValue.Type(), len, len)
for idx := 0; idx < subjectValue.Len(); idx++ {
value := Clone(subjectValue.Index(idx).Interface())
newValue.Index(idx).Set(reflect.ValueOf(value))
}
result = newValue.Interface()
} else if subjectKind == reflect.Map {
newValue := reflect.MakeMap(subjectValue.Type())
mapKeys := subjectValue.MapKeys()
for _, key := range mapKeys {
value := Clone(subjectValue.MapIndex(key).Interface())
newValue.SetMapIndex(key, reflect.ValueOf(value))
}
result = newValue.Interface()
}
return result
}
// Convert string to snake_case format
func StrToSnakeCase(str string) string {
str = regexpAnyToSnakeCase.ReplaceAllString(str, "${1}_${2}")
str = strings.Trim(str, "_")
return strings.ToLower(str)
}
// Convert string from snake_case to camelCase format
func StrToCamelCase(str string) string {
operator := func(matchedStr string) string {
matchedStr = strings.Trim(matchedStr, "_")
return strings.ToUpper(matchedStr)
}
str = regexpSnakeToCamelCase.ReplaceAllStringFunc(str, operator)
return str
}