wip
This commit is contained in:
13
generics/data.go
Normal file
13
generics/data.go
Normal file
@ -0,0 +1,13 @@
|
||||
package generics
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
func UnmarshalTo[T any](raw []byte) (*T, error) {
|
||||
var resp T
|
||||
err := json.Unmarshal(raw, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
3
generics/go.mod
Normal file
3
generics/go.mod
Normal file
@ -0,0 +1,3 @@
|
||||
module gitea.codeblob.work/pk/gut/generics
|
||||
|
||||
go 1.21.6
|
23
generics/misc.go
Normal file
23
generics/misc.go
Normal file
@ -0,0 +1,23 @@
|
||||
package generics
|
||||
|
||||
// Search for one or more needles in the haystack.
|
||||
// Returns true if any of the needles was found.
|
||||
func ContainsAny[T comparable](haystack []T, needle ...T) bool {
|
||||
for _, n := range needle {
|
||||
for _, h := range haystack {
|
||||
if h == n {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func IfThen[T any](cond bool, then T, otherwise T) T {
|
||||
if cond {
|
||||
return then
|
||||
} else {
|
||||
return otherwise
|
||||
}
|
||||
}
|
46
generics/set.go
Normal file
46
generics/set.go
Normal file
@ -0,0 +1,46 @@
|
||||
package generics
|
||||
|
||||
type Set[T comparable] map[T]struct{}
|
||||
|
||||
// New produces a new set containing the given values.
|
||||
func NewSet[T comparable](vals ...T) Set[T] {
|
||||
s := Set[T](make(map[T]struct{}))
|
||||
for _, val := range vals {
|
||||
s.Add(val)
|
||||
}
|
||||
return Set[T](s)
|
||||
}
|
||||
|
||||
// Add adds values to the set.
|
||||
func (s Set[T]) Add(vals ...T) {
|
||||
for _, val := range vals {
|
||||
s[val] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a value is already present in the set.
|
||||
func (s Set[T]) Has(val T) bool {
|
||||
_, ok := s[val]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Removes a value from the set.
|
||||
func (s Set[T]) Remove(vals ...T) {
|
||||
for _, val := range vals {
|
||||
delete(s, val)
|
||||
}
|
||||
}
|
||||
|
||||
// Number of values in the set.
|
||||
func (s Set[T]) Length() int {
|
||||
return len(s)
|
||||
}
|
||||
|
||||
// Get a slice of values in the set.
|
||||
func (s Set[T]) Values() []T {
|
||||
values := make([]T, 0, len(s))
|
||||
for k := range s {
|
||||
values = append(values, k)
|
||||
}
|
||||
return values
|
||||
}
|
Reference in New Issue
Block a user