132 lines
2.1 KiB
Go
132 lines
2.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand/v2"
|
|
"strconv"
|
|
)
|
|
|
|
func RandRange(min, max int) int {
|
|
return rand.IntN(max-min) + min
|
|
}
|
|
func Min(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
func Max(a, b int) int {
|
|
if a > b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
type Slice[T any] []T
|
|
|
|
func NewSliceFrom[T any](slice []T) Slice[T] {
|
|
s := make(Slice[T], len(slice))
|
|
copy(s[:], slice)
|
|
return s
|
|
}
|
|
func (s Slice[T]) Len() int {
|
|
return len(s)
|
|
}
|
|
func (s Slice[T]) Cap() int {
|
|
return cap(s)
|
|
}
|
|
func (s Slice[T]) Swap(i, j int) Slice[T] {
|
|
s[i], s[j] = s[j], s[i]
|
|
return s
|
|
}
|
|
func (s Slice[T]) Filter(f func(e T) bool) Slice[T] {
|
|
out := make(Slice[T], 0)
|
|
for _, v := range s {
|
|
if f(v) {
|
|
out = append(out, v)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
func (s Slice[T]) Map(f func(e T) T) Slice[T] {
|
|
out := make(Slice[T], s.Len())
|
|
for i, v := range s {
|
|
out[i] = f(v)
|
|
}
|
|
return out
|
|
}
|
|
func (s Slice[T]) Pop(index int) Slice[T] {
|
|
if index == 0 {
|
|
return s[1:]
|
|
}
|
|
out := make(Slice[T], s.Len()-index)
|
|
for i, e := range s {
|
|
if i == index {
|
|
continue
|
|
}
|
|
out[i] = e
|
|
}
|
|
return out
|
|
}
|
|
func (s Slice[T]) Push(e T) Slice[T] {
|
|
return append(s, e)
|
|
}
|
|
|
|
func (s Slice[T]) ToArray() []T {
|
|
out := make([]T, len(s))
|
|
copy(out, s)
|
|
return out
|
|
}
|
|
func (s Slice[T]) ToAnyArray() []any {
|
|
out := make([]any, len(s))
|
|
for i, v := range s {
|
|
out[i] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
func Map[S, R any](f func(s S) R, s []S) []R {
|
|
out := make([]R, len(s))
|
|
for i := range s {
|
|
out[i] = f(s[i])
|
|
}
|
|
return out
|
|
}
|
|
|
|
func PopSlice[S any](s []S, index int) []S {
|
|
if index == 0 {
|
|
return s[1:]
|
|
}
|
|
out := make([]S, 0)
|
|
for i, e := range s {
|
|
if i == index {
|
|
continue
|
|
}
|
|
out = append(out, e)
|
|
}
|
|
return out
|
|
}
|
|
func TypedSliceToAny[S any](s []S) []any {
|
|
out := make([]any, len(s))
|
|
for i := range s {
|
|
out[i] = s[i]
|
|
}
|
|
return out
|
|
}
|
|
func AppendToInt[S any](v int, s []S) []any {
|
|
out := make([]any, 1, len(s)+1)
|
|
out[0] = v
|
|
out = append(out, TypedSliceToAny(s)...)
|
|
return out
|
|
}
|
|
func StringToInt(s string) int {
|
|
i, err := strconv.Atoi(s)
|
|
if err != nil {
|
|
return -1
|
|
}
|
|
return i
|
|
}
|
|
func AnyToString[A any](a A) string {
|
|
return fmt.Sprintf("%v", a)
|
|
}
|