collections/functions.go

40 lines
1022 B
Go
Raw Permalink Normal View History

2023-07-26 22:13:21 +02:00
package collections
import "pkg.icikowski.pl/collections/functions"
2024-05-28 01:28:25 +02:00
// Of creates [Collection] of given items.
2023-07-26 22:13:21 +02:00
func Of[T any](data ...T) *Collection[T] {
return &Collection[T]{data, true}
}
2024-05-28 01:28:25 +02:00
// OfSlice creates [Collection] of given slice elements.
2023-07-26 22:13:21 +02:00
func OfSlice[T any](data []T) *Collection[T] {
return &Collection[T]{data, true}
}
2024-05-28 01:28:25 +02:00
// Iterate creates [Collection] of given number of items generated from given seed and [functions.UnaryOperator].
2023-07-26 22:13:21 +02:00
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}
}
2024-05-28 01:28:25 +02:00
// Generate creates [Collection] of given number of items generated from given [functions.Supplier].
2023-07-26 22:13:21 +02:00
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}
}