collections/functions.go

40 lines
1022 B
Go

package collections
import "pkg.icikowski.pl/collections/functions"
// Of creates [Collection] of given items.
func Of[T any](data ...T) *Collection[T] {
return &Collection[T]{data, true}
}
// OfSlice creates [Collection] of given slice elements.
func OfSlice[T any](data []T) *Collection[T] {
return &Collection[T]{data, true}
}
// Iterate creates [Collection] of given number of items generated from given seed and [functions.UnaryOperator].
func Iterate[T any](seed T, u functions.UnaryOperator[T], limit int) *Collection[T] {
if limit <= 0 {
limit = 1
}
data := []T{seed}
for i := 1; i < limit; i++ {
data = append(data, u(data[len(data)-1]))
}
return &Collection[T]{data, true}
}
// Generate creates [Collection] of given number of items generated from given [functions.Supplier].
func Generate[T any](p functions.Supplier[T], limit int) *Collection[T] {
if limit < 0 {
limit = 0
}
data := []T{}
for i := 0; i < limit; i++ {
data = append(data, p())
}
return &Collection[T]{data, true}
}