dorfylegends/backend/util/util.go

129 lines
2.4 KiB
Go
Raw Normal View History

2022-04-09 19:37:44 +03:00
package util
2022-04-21 17:25:35 +03:00
import (
"encoding/json"
"fmt"
"html/template"
2022-04-28 21:14:33 +03:00
"reflect"
2022-04-24 11:58:31 +03:00
"regexp"
2022-04-28 21:14:33 +03:00
"sort"
2022-04-21 17:25:35 +03:00
"strings"
)
2022-04-09 19:37:44 +03:00
func Keys[K comparable, V any](input map[K]V) []K {
keys := make([]K, 0, len(input))
for k := range input {
keys = append(keys, k)
}
return keys
}
func Values[K comparable, V any](input map[K]V) []V {
values := make([]V, 0, len(input))
for _, v := range input {
values = append(values, v)
}
return values
}
func ContainsAny(s string, substrings ...string) bool {
for _, substring := range substrings {
if strings.Contains(s, substring) {
return true
}
}
return false
}
2022-04-21 17:25:35 +03:00
2022-04-24 11:58:31 +03:00
func MatchesAny(s string, substrings ...string) bool {
for _, substring := range substrings {
if ok, _ := regexp.MatchString(s, substring); ok {
return true
}
}
return false
}
2022-04-21 17:25:35 +03:00
func Title(input string) string {
words := strings.Split(input, " ")
smallwords := " a an on the to of "
for index, word := range words {
if strings.Contains(smallwords, " "+word+" ") && index > 0 {
words[index] = word
} else {
words[index] = strings.Title(word)
}
}
return strings.Join(words, " ")
}
2022-04-21 23:01:18 +03:00
func Capitalize(input string) string {
2022-04-23 00:57:10 +03:00
if input == "" {
return ""
}
2022-04-21 23:01:18 +03:00
return strings.ToUpper(input[:1]) + input[1:]
}
2022-04-21 17:25:35 +03:00
func Json(obj any) template.HTML {
b, err := json.MarshalIndent(obj, "", " ")
if err != nil {
fmt.Println(err)
return ""
}
return template.HTML(`<span class="json">` + string(b) + `</span>`)
}
2022-04-21 23:01:18 +03:00
func If[T any](cond bool, v1, v2 T) T {
if cond {
return v1
} else {
return v2
}
}
func Map[U, V any](list []U, mapper func(U) V) []V {
var newList = make([]V, 0, len(list))
for _, i := range list {
newList = append(newList, mapper(i))
}
return newList
}
2022-04-23 14:31:23 +03:00
type Identifiable interface {
Id() int
}
func Find[U any](list []*U, predicate func(*U) bool) (*U, bool) {
for _, x := range list {
if predicate(x) {
return x, true
}
}
return nil, false
}
2022-04-24 13:50:07 +03:00
func FindInMap[U any](list map[int]*U, predicate func(*U) bool) (int, *U, bool) {
for id, x := range list {
if predicate(x) {
return id, x, true
}
}
return -1, nil, false
}
2022-04-28 21:14:33 +03:00
func FirstInMap(a any, b string) bool {
ks := reflect.ValueOf(a).MapKeys()
sort.Slice(ks, func(i, j int) bool { return ks[i].String() < ks[j].String() })
return ks[0].String() == b
}
2022-05-03 15:59:47 +03:00
func Strip(html template.HTML) string {
r := regexp.MustCompile(`<.*?>`)
return r.ReplaceAllString(string(html), "")
}
func String(html template.HTML) string {
return string(html)
}