flabk/pkg/coll/coll.go

70 lines
1.1 KiB
Go

// Package coll provides generic collection types and functions
package coll
func Map[T, V any](c Vector[T], f func(T) V) Vector[V] {
out := make([]V, len(c))
for index := 0; index < len(c); index++ {
out[index] = f(c[index])
}
return From(out)
}
func Filter[T any](v Vector[T], f func(T) bool) Vector[T] {
out := WithCap[T](len(v))
for _, t := range v {
if f(t) {
out = out.Push(t)
}
}
return out
}
func Take[T any](v Vector[T], howMany int) Vector[T] {
if len(v) == 0 {
return New[T]()
}
if len(v) < howMany {
howMany = len(v)
}
return From(v[:howMany-1])
}
func Any[T any](v Vector[T], f func(T) bool) bool {
for _, t := range v {
if f(t) {
return true
}
}
return false
}
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
if len(v) == 0 {
return min
}
min = v[0]
for _, t := range v {
if min > t {
min = t
}
}
return min
}
func Max[T numeric](v Vector[T]) T {
var max T
for _, t := range v {
if max < t {
max = t
}
}
return max
}