flabk/pkg/coll/coll.go

73 lines
1.3 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, c.length)
for index := 0; index < c.length; index++ {
out[index] = f(c.array[index])
}
return From(out)
}
func Filter[T any](v Vector[T], f func(T) bool) Vector[T] {
out := WithCap[T](v.length)
v.Iterate().ForEach(func(_ int, t T) {
if f(t) {
out.Push(t)
}
})
return out
}
func Take[T any](v Vector[T], howMany int) Vector[T] {
if v.length == 0 {
return New[T]()
}
if v.length < howMany {
howMany = v.length
}
return From(v.array[:howMany-1])
}
func Any[T any](v Vector[T], f func(T) bool) bool {
var found bool
v.Iterate().ForBreak(func(_ int, t T, breaker func()) {
if f(t) {
found = true
breaker()
}
})
return found
}
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 v.length == 0 {
return min
}
min = v.array[0]
v.Iterate().ForEach(func(_ int, t T) {
if min > t {
min = t
}
})
return min
}
func Max[T numeric](v Vector[T]) T {
var max T
v.Iterate().ForEach(func(_ int, t T) {
if max < t {
max = t
}
})
return max
}