2022-08-28 13:27:41 +00:00
|
|
|
package helper
|
|
|
|
|
2022-09-08 02:54:37 +00:00
|
|
|
import (
|
2022-09-22 09:21:41 +00:00
|
|
|
"fmt"
|
2022-10-13 03:09:52 +00:00
|
|
|
"math/rand"
|
2022-09-08 02:54:37 +00:00
|
|
|
"reflect"
|
2022-10-25 12:05:44 +00:00
|
|
|
"sort"
|
2022-09-08 02:54:37 +00:00
|
|
|
)
|
|
|
|
|
2022-10-13 03:09:52 +00:00
|
|
|
type IntNumber interface {
|
|
|
|
~int | ~int64 | ~int32 | ~int8 | ~int16 |
|
|
|
|
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
|
|
|
|
}
|
|
|
|
|
2022-09-26 13:25:41 +00:00
|
|
|
func ToAny[T any](v T) any {
|
|
|
|
return v
|
|
|
|
}
|
|
|
|
|
2022-08-28 13:27:41 +00:00
|
|
|
func IsContainInArr[T comparable](a T, arr []T) bool {
|
|
|
|
for _, v := range arr {
|
|
|
|
if a == v {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2022-09-08 02:54:37 +00:00
|
|
|
|
|
|
|
func StructColumn[T any, M any](arr []M, field string) (r []T) {
|
|
|
|
for i := 0; i < len(arr); i++ {
|
|
|
|
v := reflect.ValueOf(arr[i]).FieldByName(field).Interface()
|
|
|
|
if val, ok := v.(T); ok {
|
|
|
|
r = append(r, val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2022-09-15 14:35:32 +00:00
|
|
|
|
2022-10-13 03:09:52 +00:00
|
|
|
func RandNum[T IntNumber](start, end T) T {
|
|
|
|
end++
|
|
|
|
return T(rand.Int63n(int64(end-start))) + start
|
|
|
|
}
|
2022-10-25 12:05:44 +00:00
|
|
|
|
|
|
|
type anyArr[T any] struct {
|
|
|
|
data []T
|
|
|
|
fn func(i, j T) bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r anyArr[T]) Len() int {
|
|
|
|
return len(r.data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r anyArr[T]) Swap(i, j int) {
|
|
|
|
r.data[i], r.data[j] = r.data[j], r.data[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r anyArr[T]) Less(i, j int) bool {
|
|
|
|
return r.fn(r.data[i], r.data[j])
|
|
|
|
}
|
|
|
|
|
2022-11-04 02:38:59 +00:00
|
|
|
func SimpleSort[T any](arr []T, fn func(i, j T) bool) {
|
2022-10-25 12:05:44 +00:00
|
|
|
slice := anyArr[T]{
|
|
|
|
data: arr,
|
|
|
|
fn: fn,
|
|
|
|
}
|
|
|
|
sort.Sort(slice)
|
|
|
|
return
|
|
|
|
}
|
2022-11-05 12:59:49 +00:00
|
|
|
|
|
|
|
func Min[T IntNumber | ~float64 | ~float32](a ...T) T {
|
|
|
|
min := a[0]
|
|
|
|
for _, t := range a {
|
|
|
|
if min > t {
|
|
|
|
min = t
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return min
|
|
|
|
}
|
|
|
|
|
|
|
|
func Max[T IntNumber | ~float64 | ~float32](a ...T) T {
|
|
|
|
max := a[0]
|
|
|
|
for _, t := range a {
|
|
|
|
if max < t {
|
|
|
|
max = t
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return max
|
|
|
|
}
|
2022-11-06 04:04:41 +00:00
|
|
|
|
2022-11-06 04:12:57 +00:00
|
|
|
func Sum[T IntNumber | ~float64 | ~float32](a ...T) T {
|
|
|
|
s := T(0)
|
|
|
|
for _, t := range a {
|
|
|
|
s += t
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2022-11-17 06:08:26 +00:00
|
|
|
func NumberToString[T IntNumber | ~float64 | ~float32](n T) string {
|
|
|
|
return fmt.Sprintf("%v", n)
|
|
|
|
}
|