gosuki/utils/misc.go

69 lines
1.5 KiB
Go
Raw Normal View History

package utils
2018-11-20 17:33:37 +00:00
import (
"math/rand"
"strings"
)
2022-12-10 01:49:30 +00:00
2018-11-20 17:33:37 +00:00
// Return string from slice of bytes
func S(value interface{}) string {
return string(value.([]byte))
}
2022-12-10 01:49:30 +00:00
// Extends a slice of T with element `in`, like a Set
2023-01-11 11:14:10 +00:00
func Extends[T comparable](list []T, in ...T) []T {
for _, val := range in {
if !InList(list, val) {
list = append(list, val)
}
2018-11-20 17:33:37 +00:00
}
2023-01-11 11:14:10 +00:00
return list
2018-11-20 17:33:37 +00:00
}
// Return true if elm in list
2023-01-11 11:14:10 +00:00
func InList[T comparable](list []T, elm T) bool {
2018-11-20 17:33:37 +00:00
for _, v := range list {
if elm == v {
return true
}
}
return false
}
2022-12-10 01:49:30 +00:00
2022-12-11 22:06:07 +00:00
// Use to shutoff golang "unused variable comment"
func UseVar(any interface{}) {
return
}
2022-12-26 20:08:30 +00:00
// function that iterates through the list of string, for each element it
// replaces the occurence of old with new, and returns the updated list
func ReplaceInList(l []string, old string, new string) []string {
var result []string
for _, s := range l {
result = append(result, strings.Replace(s, old, new, -1))
}
return result
}
// Generate a unique random string with the specified length
func GenStringID(n int) string {
var letter = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letter[rand.Intn(len(letter))]
}
return string(b)
}
2023-01-11 11:14:10 +00:00
// map takes a list and a function and returns a new list
func Map[T , U comparable](f func(item T) U, list []T) []U {
var newList []U
for _, v := range list {
newList = append(newList, f(v))
}
return newList
}