flabk/pkg/coll/coll.go

70 lines
1.1 KiB
Go
Raw Normal View History

2022-08-02 13:18:08 +01:00
// Package coll provides generic collection types and functions
package coll
func Map[T, V any](c Vector[T], f func(T) V) Vector[V] {
2022-08-02 15:49:10 +01:00
out := make([]V, len(c))
for index := 0; index < len(c); index++ {
out[index] = f(c[index])
2022-08-02 13:18:08 +01:00
}
return From(out)
}
func Filter[T any](v Vector[T], f func(T) bool) Vector[T] {
2022-08-02 15:49:10 +01:00
out := WithCap[T](len(v))
for _, t := range v {
2022-08-02 13:18:08 +01:00
if f(t) {
2022-08-02 15:49:10 +01:00
out = out.Push(t)
2022-08-02 13:18:08 +01:00
}
2022-08-02 15:49:10 +01:00
}
2022-08-02 13:18:08 +01:00
return out
}
func Take[T any](v Vector[T], howMany int) Vector[T] {
2022-08-02 15:49:10 +01:00
if len(v) == 0 {
2022-08-02 13:18:08 +01:00
return New[T]()
}
2022-08-02 15:49:10 +01:00
if len(v) < howMany {
howMany = len(v)
2022-08-02 13:18:08 +01:00
}
2022-08-02 15:49:10 +01:00
return From(v[:howMany-1])
2022-08-02 13:18:08 +01:00
}
func Any[T any](v Vector[T], f func(T) bool) bool {
2022-08-02 15:49:10 +01:00
for _, t := range v {
2022-08-02 13:18:08 +01:00
if f(t) {
2022-08-02 15:49:10 +01:00
return true
2022-08-02 13:18:08 +01:00
}
2022-08-02 15:49:10 +01:00
}
return false
2022-08-02 13:18:08 +01:00
}
type numeric interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}
func Min[T numeric](v Vector[T]) T {
var min T
2022-08-02 15:49:10 +01:00
if len(v) == 0 {
2022-08-02 13:18:08 +01:00
return min
}
2022-08-02 15:49:10 +01:00
min = v[0]
for _, t := range v {
2022-08-02 13:18:08 +01:00
if min > t {
min = t
}
2022-08-02 15:49:10 +01:00
}
2022-08-02 13:18:08 +01:00
return min
}
func Max[T numeric](v Vector[T]) T {
var max T
2022-08-02 15:49:10 +01:00
for _, t := range v {
2022-08-02 13:18:08 +01:00
if max < t {
max = t
}
2022-08-02 15:49:10 +01:00
}
2022-08-02 13:18:08 +01:00
return max
}