Documentation
¶
Overview ¶
Package collect chains lazy operations on a sequence of values, in the manner of Laravel's LazyCollection.
A Collection wraps an iter.Seq. Its methods build a new sequence and run nothing: the values flow only when a terminal method, such as Collection.All, or a range over Collection.Seq reads them.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/mpyw/collect"
)
func main() {
type order struct {
Customer string
Item string
Price int
}
orders := collect.Of(
order{"alice", "desk", 200},
order{"bob", "chair", 100},
order{"alice", "lamp", 40},
order{"carol", "sofa", 300},
order{"bob", "pen", 5},
)
price := func(o order) int { return o.Price }
customer := func(o order) string { return o.Customer }
item := func(o order) string { return o.Item }
// Chain Filter and Map. Map may change the type of the values.
cheap := orders.
Filter(func(o order) bool { return o.Price < 100 }).
Map(func(o order) string { return o.Item }).
All()
fmt.Println("cheap:", cheap) // cheap: [lamp pen]
// A method that needs numbers or an order takes a key function.
fmt.Println("total:", orders.SumBy(price)) // total: 645
top, ok := orders.SortByDesc(price).First()
fmt.Println("top:", top.Item, ok) // top: sofa true
// GroupBy nests: each group is a Collection with every method.
for name, group := range orders.GroupBy(customer).Seq() {
fmt.Println(name, group.Count(), group.SumBy(price)) // alice 2 240, then bob 2 105, then carol 1 300
}
// Keys are opt-in. KeyBy gives each value one.
sofa, _ := orders.KeyBy(item).Get("sofa")
fmt.Println("sofa:", sofa.Customer) // sofa: carol
// Identity stands in for the key function when the values are their own keys.
unique := collect.Of(3, 1, 2, 3, 1).UniqueBy(collect.Identity).SortBy(collect.Identity)
fmt.Println("unique:", unique.All()) // unique: [1 2 3]
// Chunk returns a Collection of collections.
for chunk := range unique.Chunk(2).Seq() {
fmt.Println("chunk:", chunk.All()) // chunk: [1 2], then chunk: [3]
}
// A lookup that may find nothing returns a bool. One that can fail in
// more ways returns an error.
_, err := orders.Filter(func(o order) bool { return o.Customer == "dave" }).Sole()
fmt.Println("dave:", errors.Is(err, collect.ErrItemNotFound)) // dave: true
// It is lazy, so an endless source is fine while something ends it.
naturals := func(yield func(int) bool) {
for n := 1; ; n++ {
if !yield(n) {
return
}
}
}
squares := collect.FromSeq(naturals).Map(func(n int) int { return n * n }).Take(5).All()
fmt.Println("squares:", squares) // squares: [1 4 9 16 25]
}
Output: cheap: [lamp pen] total: 645 top: sofa true alice 2 240 bob 2 105 carol 1 300 sofa: carol unique: [1 2 3] chunk: [1 2] chunk: [3] dave: true squares: [1 4 9 16 25]
Example (Reuse) ¶
A collection reads its source again on each read. One from Of, FromSlice or FromMap reads the same values every time, so it needs no Remember. A source that can be read only once, such as a database cursor, is used up by the first read: Remember keeps what it reads.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
evens := collect.Of(1, 2, 3, 4).Filter(func(n int) bool { return n%2 == 0 })
fmt.Println(evens.All()) // [2 4]
fmt.Println(evens.All()) // [2 4], read again from the start
cursor := func() func(func(int) bool) {
used := false
return func(yield func(int) bool) {
if used {
return
}
used = true
for n := 1; n <= 3; n++ {
if !yield(n) {
return
}
}
}
}
once := collect.FromSeq(cursor())
fmt.Println(once.All()) // [1 2 3]
fmt.Println(once.All()) // [], the cursor is used up
kept := collect.FromSeq(cursor()).Remember()
fmt.Println(kept.All()) // [1 2 3]
fmt.Println(kept.All()) // [1 2 3], from what Remember kept
}
Output: [2 4] [2 4] [1 2 3] [] [1 2 3] [1 2 3]
Index ¶
- Variables
- func Identity[T any](v T) T
- func Key[K, V any](k K, _ V) K
- func Value[K, V any](_ K, v V) V
- type Collection
- func (c Collection[T]) After(match func(T) bool) (T, bool)
- func (c Collection[T]) All() []T
- func (c Collection[T]) AvgBy[N Number](f func(T) N) (float64, bool)
- func (c Collection[T]) Before(match func(T) bool) (T, bool)
- func (c Collection[T]) Chunk[C interface{ ... }](size int) Collection[C]
- func (c Collection[T]) ChunkBy[K comparable, C interface{ ... }](f func(T) K) Collection[C]
- func (c Collection[T]) ChunkWhile[C interface{ ... }](keep func(v T, chunk Collection[T]) bool) Collection[C]
- func (c Collection[T]) Concat(others ...Collection[T]) Collection[T]
- func (c Collection[T]) Contains(match func(T) bool) bool
- func (c Collection[T]) Count() int
- func (c Collection[T]) CountBy[K comparable](f func(T) K) KeyedCollection[K, int]
- func (c Collection[T]) CrossJoin[U any, Z interface{ ... }](other Collection[U]) Collection[Z]
- func (c Collection[T]) DiffBy[K comparable](other Collection[T], f func(T) K) Collection[T]
- func (c Collection[T]) DiffFunc(other Collection[T], eq func(a, b T) bool) Collection[T]
- func (c Collection[T]) DoesntContain(match func(T) bool) bool
- func (c Collection[T]) DuplicatesBy[K comparable](f func(T) K) Collection[K]
- func (c Collection[T]) Each(f func(T))
- func (c Collection[T]) Eager() Collection[T]
- func (c Collection[T]) Ensure[U any]() (Collection[U], error)
- func (c Collection[T]) Entries[E interface{ ... }]() Collection[E]
- func (c Collection[T]) Every(match func(T) bool) bool
- func (c Collection[T]) Filter(keep func(T) bool) Collection[T]
- func (c Collection[T]) First() (T, bool)
- func (c Collection[T]) FirstWhere(match func(T) bool) (T, bool)
- func (c Collection[T]) FlatMap[U any](f func(T) Collection[U]) Collection[U]
- func (c Collection[T]) ForPage(page, perPage int) Collection[T]
- func (c Collection[T]) GroupBy[K comparable, C interface{ ... }](f func(T) K) KeyedCollection[K, C]
- func (c Collection[T]) HasMany() bool
- func (c Collection[T]) HasSole() bool
- func (c Collection[T]) ImplodeBy[S ~string](f func(T) S, sep string) string
- func (c Collection[T]) IntersectBy[K comparable](other Collection[T], f func(T) K) Collection[T]
- func (c Collection[T]) IntersectFunc(other Collection[T], eq func(a, b T) bool) Collection[T]
- func (c Collection[T]) IsEmpty() bool
- func (c Collection[T]) IsNotEmpty() bool
- func (c Collection[T]) JoinBy[S ~string](f func(T) S, sep string) string
- func (c Collection[T]) JoinFinalBy[S ~string](f func(T) S, glue, finalGlue string) string
- func (c Collection[T]) KeyBy[K comparable](f func(T) K) KeyedCollection[K, T]
- func (c Collection[T]) Keyed() KeyedCollection[int, T]
- func (c Collection[T]) Last() (T, bool)
- func (c Collection[T]) Map[U any](f func(T) U) Collection[U]
- func (c Collection[T]) MapToGroups[K comparable, U any](f func(T) (K, U)) KeyedCollection[K, Collection[U]]
- func (c Collection[T]) MapWithKeys[K comparable, U any](f func(T) (K, U)) KeyedCollection[K, U]
- func (c Collection[T]) MarshalJSONTo(enc *jsontext.Encoder) error
- func (c Collection[T]) MaxBy[K cmp.Ordered](f func(T) K) (K, bool)
- func (c Collection[T]) MedianBy[N Number](f func(T) N) (float64, bool)
- func (c Collection[T]) MinBy[K cmp.Ordered](f func(T) K) (K, bool)
- func (c Collection[T]) ModeBy[K comparable](f func(T) K) Collection[K]
- func (c Collection[T]) Multiply(n int) Collection[T]
- func (c Collection[T]) MustEnsure[U any]() Collection[U]
- func (c Collection[T]) MustFirst() T
- func (c Collection[T]) MustLast() T
- func (c Collection[T]) MustSole() T
- func (c Collection[T]) Nth(step, offset int) Collection[T]
- func (c Collection[T]) Pad(size int, v T) Collection[T]
- func (c Collection[T]) Partition(match func(T) bool) (Collection[T], Collection[T])
- func (c Collection[T]) Percentage(match func(T) bool, precision int) (float64, bool)
- func (c Collection[T]) Pipe[U any](f func(Collection[T]) U) U
- func (c Collection[T]) PipeThrough(fs ...func(Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) Random() (T, bool)
- func (c Collection[T]) RandomN(n int) (Collection[T], error)
- func (c Collection[T]) Reduce[A any](f func(A, T) A, initial A) A
- func (c Collection[T]) Reject(drop func(T) bool) Collection[T]
- func (c Collection[T]) Remember() Collection[T]
- func (c Collection[T]) Reverse() Collection[T]
- func (c Collection[T]) Search(match func(T) bool) (int, bool)
- func (c Collection[T]) Seq() iter.Seq[T]
- func (c Collection[T]) Shuffle() Collection[T]
- func (c Collection[T]) Skip(n int) Collection[T]
- func (c Collection[T]) SkipUntil(match func(T) bool) Collection[T]
- func (c Collection[T]) SkipWhile(match func(T) bool) Collection[T]
- func (c Collection[T]) Slice(offset, length int) Collection[T]
- func (c Collection[T]) Sliding[C interface{ ... }](size, step int) Collection[C]
- func (c Collection[T]) Sole() (T, error)
- func (c Collection[T]) SortBy[K cmp.Ordered](f func(T) K) Collection[T]
- func (c Collection[T]) SortByDesc[K cmp.Ordered](f func(T) K) Collection[T]
- func (c Collection[T]) SortFunc(cmp func(a, b T) int) Collection[T]
- func (c Collection[T]) Split[C interface{ ... }](n int) Collection[C]
- func (c Collection[T]) SplitIn[C interface{ ... }](n int) Collection[C]
- func (c Collection[T]) SumBy[N Number](f func(T) N) N
- func (c Collection[T]) Take(n int) Collection[T]
- func (c Collection[T]) TakeUntil(match func(T) bool) Collection[T]
- func (c Collection[T]) TakeWhile(match func(T) bool) Collection[T]
- func (c Collection[T]) TapEach(f func(T)) Collection[T]
- func (c Collection[T]) UniqueBy[K comparable](f func(T) K) Collection[T]
- func (c Collection[T]) Unless(cond bool, f func(Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) When(cond bool, f func(Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) WhereBetweenBy[K cmp.Ordered](f func(T) K, low, high K) Collection[T]
- func (c Collection[T]) WhereInBy[K comparable](f func(T) K, keys ...K) Collection[T]
- func (c Collection[T]) WhereInstanceOf[U any]() Collection[U]
- func (c Collection[T]) WhereNotBetweenBy[K cmp.Ordered](f func(T) K, low, high K) Collection[T]
- func (c Collection[T]) WhereNotInBy[K comparable](f func(T) K, keys ...K) Collection[T]
- func (c Collection[T]) Zip2[U any, Z interface{ ... }](other Collection[U]) Collection[Z]
- func (c Collection[T]) Zip3[U, V any, Z interface{ ... }](us Collection[U], vs Collection[V]) Collection[Z]
- func (c Collection[T]) Zip4[U, V, W any, Z interface{ ... }](us Collection[U], vs Collection[V], ws Collection[W]) Collection[Z]
- func (c Collection[T]) Zip5[U, V, W, X any, Z interface{ ... }](us Collection[U], vs Collection[V], ws Collection[W], xs Collection[X]) Collection[Z]
- type Entry
- type KeyedCollection
- func Combine[K comparable, V any](keys Collection[K], values Collection[V]) (KeyedCollection[K, V], error)
- func FromEntries[K comparable, V any](c Collection[Entry[K, V]]) KeyedCollection[K, V]
- func FromMap[K comparable, V any](m map[K]V) KeyedCollection[K, V]
- func FromSeq2[K comparable, V any](seq iter.Seq2[K, V]) KeyedCollection[K, V]
- func MustCombine[K comparable, V any](keys Collection[K], values Collection[V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) After(match func(K, V) bool) (K, V, bool)
- func (c KeyedCollection[K, V]) AvgBy[N Number](f func(K, V) N) (float64, bool)
- func (c KeyedCollection[K, V]) Before(match func(K, V) bool) (K, V, bool)
- func (c KeyedCollection[K, V]) Chunk[C interface{ ... }](size int) Collection[C]
- func (c KeyedCollection[K, V]) ChunkBy[E comparable, C interface{ ... }](f func(K, V) E) Collection[C]
- func (c KeyedCollection[K, V]) ChunkWhile[C interface{ ... }](keep func(k K, v V, chunk KeyedCollection[K, V]) bool) Collection[C]
- func (c KeyedCollection[K, V]) Concat(others ...KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Contains(match func(K, V) bool) bool
- func (c KeyedCollection[K, V]) Count() int
- func (c KeyedCollection[K, V]) CountBy[G comparable](f func(K, V) G) KeyedCollection[G, int]
- func (c KeyedCollection[K, V]) DiffAssocBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) DiffBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) DiffFunc(other KeyedCollection[K, V], eq func(a, b V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) DiffKeys(other KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) DoesntContain(match func(K, V) bool) bool
- func (c KeyedCollection[K, V]) DuplicatesBy[E comparable](f func(K, V) E) KeyedCollection[K, E]
- func (c KeyedCollection[K, V]) Each(f func(K, V))
- func (c KeyedCollection[K, V]) Eager() KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Ensure[U any]() (KeyedCollection[K, U], error)
- func (c KeyedCollection[K, V]) Entries[E interface{ ... }]() Collection[E]
- func (c KeyedCollection[K, V]) Every(match func(K, V) bool) bool
- func (c KeyedCollection[K, V]) Except(keys ...K) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Filter(keep func(K, V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) First() (K, V, bool)
- func (c KeyedCollection[K, V]) FirstWhere(match func(K, V) bool) (K, V, bool)
- func (c KeyedCollection[K, V]) FlatMap[K2 comparable, U any](f func(K, V) KeyedCollection[K2, U]) KeyedCollection[K2, U]
- func (c KeyedCollection[K, V]) FlipBy[K2 comparable](f func(V) K2) KeyedCollection[K2, K]
- func (c KeyedCollection[K, V]) ForPage(page, perPage int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Get(k K) (V, bool)
- func (c KeyedCollection[K, V]) GroupBy[G comparable, C interface{ ... }](f func(K, V) G) KeyedCollection[G, C]
- func (c KeyedCollection[K, V]) Has(keys ...K) bool
- func (c KeyedCollection[K, V]) HasAny(keys ...K) bool
- func (c KeyedCollection[K, V]) HasMany() bool
- func (c KeyedCollection[K, V]) HasSole() bool
- func (c KeyedCollection[K, V]) ImplodeBy[S ~string](f func(K, V) S, sep string) string
- func (c KeyedCollection[K, V]) IntersectAssocBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) IntersectBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) IntersectFunc(other KeyedCollection[K, V], eq func(a, b V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) IntersectKeys(other KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) IsEmpty() bool
- func (c KeyedCollection[K, V]) IsNotEmpty() bool
- func (c KeyedCollection[K, V]) JoinBy[S ~string](f func(K, V) S, sep string) string
- func (c KeyedCollection[K, V]) JoinFinalBy[S ~string](f func(K, V) S, glue, finalGlue string) string
- func (c KeyedCollection[K, V]) KeyBy[K2 comparable](f func(K, V) K2) KeyedCollection[K2, V]
- func (c KeyedCollection[K, V]) Keys() Collection[K]
- func (c KeyedCollection[K, V]) Last() (K, V, bool)
- func (c KeyedCollection[K, V]) Map[U any](f func(K, V) U) KeyedCollection[K, U]
- func (c KeyedCollection[K, V]) MapToGroups[G comparable, U any](f func(K, V) (G, U)) KeyedCollection[G, Collection[U]]
- func (c KeyedCollection[K, V]) MapWithKeys[K2 comparable, U any](f func(K, V) (K2, U)) KeyedCollection[K2, U]
- func (c KeyedCollection[K, V]) MarshalJSONTo(enc *jsontext.Encoder) error
- func (c KeyedCollection[K, V]) MaxBy[O cmp.Ordered](f func(K, V) O) (O, bool)
- func (c KeyedCollection[K, V]) MedianBy[N Number](f func(K, V) N) (float64, bool)
- func (c KeyedCollection[K, V]) MinBy[O cmp.Ordered](f func(K, V) O) (O, bool)
- func (c KeyedCollection[K, V]) ModeBy[E comparable](f func(K, V) E) Collection[E]
- func (c KeyedCollection[K, V]) Multiply(n int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) MustEnsure[U any]() KeyedCollection[K, U]
- func (c KeyedCollection[K, V]) MustFirst() (K, V)
- func (c KeyedCollection[K, V]) MustGet(k K) V
- func (c KeyedCollection[K, V]) MustLast() (K, V)
- func (c KeyedCollection[K, V]) MustSole() (K, V)
- func (c KeyedCollection[K, V]) Nth(step, offset int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Only(keys ...K) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Partition(match func(K, V) bool) (KeyedCollection[K, V], KeyedCollection[K, V])
- func (c KeyedCollection[K, V]) Percentage(match func(K, V) bool, precision int) (float64, bool)
- func (c KeyedCollection[K, V]) Pipe[U any](f func(KeyedCollection[K, V]) U) U
- func (c KeyedCollection[K, V]) PipeThrough(fs ...func(KeyedCollection[K, V]) KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Random() (K, V, bool)
- func (c KeyedCollection[K, V]) RandomN(n int) (KeyedCollection[K, V], error)
- func (c KeyedCollection[K, V]) Reduce[A any](f func(A, K, V) A, initial A) A
- func (c KeyedCollection[K, V]) Reject(drop func(K, V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Remember() KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Replace(other KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Reverse() KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Search(match func(K, V) bool) (K, bool)
- func (c KeyedCollection[K, V]) Seq() iter.Seq2[K, V]
- func (c KeyedCollection[K, V]) Shuffle() KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Skip(n int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SkipUntil(match func(K, V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SkipWhile(match func(K, V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Slice(offset, length int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Sliding[C interface{ ... }](size, step int) Collection[C]
- func (c KeyedCollection[K, V]) Sole() (K, V, error)
- func (c KeyedCollection[K, V]) SortBy[O cmp.Ordered](f func(K, V) O) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SortByDesc[O cmp.Ordered](f func(K, V) O) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SortFunc(cmp func(ak K, av V, bk K, bv V) int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SortKeysBy[O cmp.Ordered](f func(K) O) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SortKeysByDesc[O cmp.Ordered](f func(K) O) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) SortKeysFunc(cmp func(a, b K) int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Split[C interface{ ... }](n int) Collection[C]
- func (c KeyedCollection[K, V]) SplitIn[C interface{ ... }](n int) Collection[C]
- func (c KeyedCollection[K, V]) SumBy[N Number](f func(K, V) N) N
- func (c KeyedCollection[K, V]) Take(n int) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) TakeUntil(match func(K, V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) TakeWhile(match func(K, V) bool) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) TapEach(f func(K, V)) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) ToMap() map[K]V
- func (c KeyedCollection[K, V]) Union(other KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) UniqueBy[E comparable](f func(K, V) E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Unless(cond bool, f func(KeyedCollection[K, V]) KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) Values() Collection[V]
- func (c KeyedCollection[K, V]) When(cond bool, f func(KeyedCollection[K, V]) KeyedCollection[K, V]) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) WhereBetweenBy[E cmp.Ordered](f func(K, V) E, low, high E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) WhereInBy[E comparable](f func(K, V) E, keys ...E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) WhereInstanceOf[U any]() KeyedCollection[K, U]
- func (c KeyedCollection[K, V]) WhereNotBetweenBy[E cmp.Ordered](f func(K, V) E, low, high E) KeyedCollection[K, V]
- func (c KeyedCollection[K, V]) WhereNotInBy[E comparable](f func(K, V) E, keys ...E) KeyedCollection[K, V]
- type Number
- type Tuple2
- type Tuple3
- type Tuple4
- type Tuple5
Examples ¶
- Package
- Package (Reuse)
- Collection.After
- Collection.All
- Collection.AvgBy
- Collection.Before
- Collection.Chunk
- Collection.Chunk (Nested)
- Collection.ChunkBy
- Collection.ChunkWhile
- Collection.Concat
- Collection.Contains
- Collection.Count
- Collection.CountBy
- Collection.CrossJoin
- Collection.DiffBy
- Collection.DiffFunc
- Collection.DoesntContain
- Collection.DuplicatesBy
- Collection.Each
- Collection.Eager
- Collection.Ensure
- Collection.Entries
- Collection.Every
- Collection.Filter
- Collection.First
- Collection.FirstWhere
- Collection.FlatMap
- Collection.FlatMap (Flatten)
- Collection.ForPage
- Collection.GroupBy
- Collection.HasMany
- Collection.HasSole
- Collection.ImplodeBy
- Collection.IntersectBy
- Collection.IntersectFunc
- Collection.IsEmpty
- Collection.IsEmpty (Remember)
- Collection.IsNotEmpty
- Collection.JoinBy
- Collection.JoinFinalBy
- Collection.KeyBy
- Collection.Keyed
- Collection.Last
- Collection.Map
- Collection.Map (NewType)
- Collection.MapToGroups
- Collection.MapWithKeys
- Collection.MarshalJSONTo
- Collection.MaxBy
- Collection.MedianBy
- Collection.MinBy
- Collection.ModeBy
- Collection.Multiply
- Collection.MustEnsure
- Collection.MustFirst
- Collection.MustLast
- Collection.MustSole
- Collection.Nth
- Collection.Pad
- Collection.Partition
- Collection.Percentage
- Collection.Pipe
- Collection.PipeThrough
- Collection.Random
- Collection.RandomN
- Collection.Reduce
- Collection.Reject
- Collection.Remember
- Collection.Reverse
- Collection.Search
- Collection.Seq
- Collection.Shuffle
- Collection.Skip
- Collection.SkipUntil
- Collection.SkipWhile
- Collection.Slice
- Collection.Sliding
- Collection.Sole
- Collection.SortBy
- Collection.SortByDesc
- Collection.SortFunc
- Collection.Split
- Collection.SplitIn
- Collection.SumBy
- Collection.Take
- Collection.TakeUntil
- Collection.TakeWhile
- Collection.TapEach
- Collection.UniqueBy
- Collection.Unless
- Collection.When
- Collection.WhereBetweenBy
- Collection.WhereInBy
- Collection.WhereInstanceOf
- Collection.WhereNotBetweenBy
- Collection.WhereNotInBy
- Collection.Zip2
- Collection.Zip3
- Collection.Zip4
- Collection.Zip5
- Combine
- E
- FromEntries
- FromMap
- FromSeq
- FromSeq2
- FromSlice
- Identity
- Key
- KeyedCollection.After
- KeyedCollection.AvgBy
- KeyedCollection.Before
- KeyedCollection.Chunk
- KeyedCollection.ChunkBy
- KeyedCollection.ChunkWhile
- KeyedCollection.Concat
- KeyedCollection.Contains
- KeyedCollection.Count
- KeyedCollection.CountBy
- KeyedCollection.DiffAssocBy
- KeyedCollection.DiffBy
- KeyedCollection.DiffFunc
- KeyedCollection.DiffKeys
- KeyedCollection.DoesntContain
- KeyedCollection.DuplicatesBy
- KeyedCollection.Each
- KeyedCollection.Eager
- KeyedCollection.Ensure
- KeyedCollection.Entries
- KeyedCollection.Every
- KeyedCollection.Except
- KeyedCollection.Filter
- KeyedCollection.First
- KeyedCollection.FirstWhere
- KeyedCollection.FlatMap
- KeyedCollection.FlipBy
- KeyedCollection.ForPage
- KeyedCollection.Get
- KeyedCollection.GroupBy
- KeyedCollection.Has
- KeyedCollection.HasAny
- KeyedCollection.HasMany
- KeyedCollection.HasSole
- KeyedCollection.ImplodeBy
- KeyedCollection.IntersectAssocBy
- KeyedCollection.IntersectBy
- KeyedCollection.IntersectFunc
- KeyedCollection.IntersectKeys
- KeyedCollection.IsEmpty
- KeyedCollection.IsNotEmpty
- KeyedCollection.JoinBy
- KeyedCollection.JoinFinalBy
- KeyedCollection.KeyBy
- KeyedCollection.Keys
- KeyedCollection.Last
- KeyedCollection.Map
- KeyedCollection.MapToGroups
- KeyedCollection.MapWithKeys
- KeyedCollection.MarshalJSONTo
- KeyedCollection.MaxBy
- KeyedCollection.MedianBy
- KeyedCollection.MinBy
- KeyedCollection.ModeBy
- KeyedCollection.Multiply
- KeyedCollection.MustEnsure
- KeyedCollection.MustFirst
- KeyedCollection.MustGet
- KeyedCollection.MustLast
- KeyedCollection.MustSole
- KeyedCollection.Nth
- KeyedCollection.Only
- KeyedCollection.Partition
- KeyedCollection.Percentage
- KeyedCollection.Pipe
- KeyedCollection.PipeThrough
- KeyedCollection.Random
- KeyedCollection.RandomN
- KeyedCollection.Reduce
- KeyedCollection.Reject
- KeyedCollection.Remember
- KeyedCollection.Replace
- KeyedCollection.Reverse
- KeyedCollection.Search
- KeyedCollection.Seq
- KeyedCollection.Shuffle
- KeyedCollection.Skip
- KeyedCollection.SkipUntil
- KeyedCollection.SkipWhile
- KeyedCollection.Slice
- KeyedCollection.Sliding
- KeyedCollection.Sole
- KeyedCollection.SortBy
- KeyedCollection.SortByDesc
- KeyedCollection.SortFunc
- KeyedCollection.SortKeysBy
- KeyedCollection.SortKeysByDesc
- KeyedCollection.SortKeysFunc
- KeyedCollection.Split
- KeyedCollection.SplitIn
- KeyedCollection.SumBy
- KeyedCollection.Take
- KeyedCollection.TakeUntil
- KeyedCollection.TakeWhile
- KeyedCollection.TapEach
- KeyedCollection.ToMap
- KeyedCollection.Union
- KeyedCollection.UniqueBy
- KeyedCollection.Unless
- KeyedCollection.Values
- KeyedCollection.When
- KeyedCollection.WhereBetweenBy
- KeyedCollection.WhereInBy
- KeyedCollection.WhereInstanceOf
- KeyedCollection.WhereNotBetweenBy
- KeyedCollection.WhereNotInBy
- MustCombine
- Of
- Range
- RangeStep
- T2
- T3
- T4
- T5
- Times
- Value
Constants ¶
This section is empty.
Variables ¶
var ( // ErrItemNotFound is the error of [Collection.Sole] when there is no // value, and the panic of [Collection.MustFirst], [Collection.MustLast], // [KeyedCollection.MustGet] and the like. It is Laravel's // ItemNotFoundException. ErrItemNotFound = errors.New("collect: item not found") // ErrMultipleItemsFound is the error of [Collection.Sole], and the panic // of [Collection.MustSole], when there is more than one value. It is // Laravel's MultipleItemsFoundException. ErrMultipleItemsFound = errors.New("collect: multiple items found") // ErrNotEnoughItems is the error of [Collection.RandomN] when it is // asked for more values than there are. ErrNotEnoughItems = errors.New("collect: not enough items") // ErrInvalidArgument is wrapped by the panic of a method given an // argument that cannot be right, such as Chunk(0) or RangeStep's step 0, // as slices.Chunk panics. ErrInvalidArgument = errors.New("collect: invalid argument") // ErrUnsupportedKey is the error of [KeyedCollection.MarshalJSONTo] for // a key that encodes as neither a JSON string, number nor boolean. ErrUnsupportedKey = errors.New("collect: unsupported key") // ErrUnexpectedValue is the error of [Collection.Ensure], and the panic // of [Collection.MustEnsure], for a value of another type. It is // Laravel's UnexpectedValueException. ErrUnexpectedValue = errors.New("collect: unexpected value") // ErrLengthMismatch is the error of [Combine], and the panic of // [MustCombine], when there are not as many values as keys. It is the // ValueError of Laravel's combine. ErrLengthMismatch = errors.New("collect: lengths do not match") )
Functions ¶
func Identity ¶
func Identity[T any](v T) T
Identity returns v. Pass it where a method takes a key function and the values are their own keys: c.SumBy(collect.Identity) sums a Collection[int], as Laravel's sum() does. Go infers its type from the collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(3, 1, 2)
fmt.Println(c.SumBy(collect.Identity))
fmt.Println(c.SortBy(collect.Identity).All())
}
Output: 6 [1 2 3]
func Key ¶
func Key[K, V any](k K, _ V) K
Key returns k. It is Identity for the keys of a KeyedCollection: k.SortBy(collect.Key) sorts the pairs by key.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"b": 2, "a": 1, "c": 3}).SortBy(collect.Key)
fmt.Println(c.Keys().All())
}
Output: [a b c]
func Value ¶
func Value[K, V any](_ K, v V) V
Value returns v. It is Identity for a KeyedCollection, whose methods take a key and a value: k.SumBy(collect.Value) sums the values.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
prices := collect.FromMap(map[string]int{"desk": 200, "chair": 100})
fmt.Println(prices.SumBy(collect.Value))
}
Output: 300
Types ¶
type Collection ¶
type Collection[T any] struct { // contains filtered or unexported fields }
Collection is a lazy sequence of values of type T.
A method whose result nests T, such as Collection.Chunk, declares a type parameter C that only T's collection satisfies, and returns Collection[C]. Go infers C, so a caller never writes it. Returning Collection[Collection[T]] itself would not compile: the compiler would instantiate the methods of Collection[Collection[T]], and so of Collection[Collection[Collection[T]]], without end ("instantiation cycle", golang/go#80172). C is instantiated only by a call, so only as deep as calls go.
The zero value is an empty collection. A collection is as reusable as the sequence it reads: one from Of or FromSlice can be read any number of times, one from FromSeq as many times as its sequence allows.
func FromSeq ¶
func FromSeq[T any](seq iter.Seq[T]) Collection[T]
FromSeq returns a collection that reads seq. A nil seq is empty.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
naturals := func(yield func(int) bool) {
for i := 1; ; i++ {
if !yield(i) {
return
}
}
}
squares := collect.FromSeq(naturals).
Map(func(n int) int { return n * n }).
Take(5).
All()
fmt.Println(squares)
}
Output: [1 4 9 16 25]
func FromSlice ¶
func FromSlice[T any](s []T) Collection[T]
FromSlice returns a collection that reads s, with no copy. Each read sees s as it is then, as slices.Values does. Of copies instead.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
values := []int{1, 2, 3}
c := collect.FromSlice(values)
values[0] = 100 // FromSlice did not copy, so the next read sees it.
fmt.Println(c.All())
}
Output: [100 2 3]
func Of ¶
func Of[T any](values ...T) Collection[T]
Of returns a collection of values. It copies values, so changing the slice later does not change the collection. FromSlice reads a slice without a copy.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
values := []int{1, 2, 3}
c := collect.Of(values...)
values[0] = 100 // Of copied values, so c does not change.
fmt.Println(c.All())
fmt.Println(collect.Of("a", "b").All())
}
Output: [1 2 3] [a b]
func Range ¶
func Range[N Number](from, to N) Collection[N]
Range returns the numbers from from to to, both included, a step of 1 apart. It counts down if to is less than from.
Example ¶
Laravel's example of range, and counting down.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(3, 6).All())
fmt.Println(collect.Range(6, 3).All())
}
Output: [3 4 5 6] [6 5 4 3]
func RangeStep ¶
func RangeStep[N Number](from, to, step N) Collection[N]
RangeStep returns the numbers from from to to, both included, step apart. It counts down if to is less than from, whatever the sign of step.
An integer range adds step to each number. A float range computes each number as from plus i times step, as PHP's range does, so that rounding does not build up: RangeStep(0, 1, 0.1) ends at 1. Laravel's lazy range adds the step instead, and ends at 0.9999999999999999.
It stops before a number that would wrap around the end of N, or that would not change, as with a float step too small for from. A NaN in any argument gives no numbers. It panics with an error that wraps ErrInvalidArgument if step is 0, as Laravel throws.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.RangeStep(0, 10, 3).All())
fmt.Println(collect.RangeStep(0, 1, 0.25).All())
}
Output: [0 3 6 9] [0 0.25 0.5 0.75 1]
func Times ¶
func Times[T any](n int, f func(int) T) Collection[T]
Times returns what f returns for 1 to n, in order, as Laravel's times does. It is empty if n is less than 1. Use Range for the numbers themselves.
Example ¶
Laravel's example of times.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Times(5, func(n int) int { return n * 9 }).All())
}
Output: [9 18 27 36 45]
func (Collection[T]) After ¶
func (c Collection[T]) After(match func(T) bool) (T, bool)
After returns the value just after the first for which match returns true. It is false if no value matches, or if the last value is the first that does.
Example ¶
Laravel's example of after.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
v, ok := collect.Of(1, 2, 3, 4, 5).After(func(n int) bool { return n == 3 })
fmt.Println(v, ok)
}
Output: 4 true
func (Collection[T]) All ¶
func (c Collection[T]) All() []T
All reads the collection into a new slice. It is Laravel's all. Note that slices.All is an iterator: here, Collection.Seq is.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3).All())
}
Output: [1 2 3]
func (Collection[T]) AvgBy ¶
func (c Collection[T]) AvgBy[N Number](f func(T) N) (float64, bool)
AvgBy returns the mean of the numbers f returns for the values. It is false for an empty collection. Pass Identity for a collection of numbers.
Example ¶
Laravel's examples of avg.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
avg, ok := collect.Of(1, 1, 2, 4).AvgBy(collect.Identity)
fmt.Println(avg, ok)
type score struct{ Foo int }
avg, ok = collect.Of(score{10}, score{10}, score{20}, score{40}).AvgBy(func(s score) int { return s.Foo })
fmt.Println(avg, ok)
}
Output: 2 true 20 true
func (Collection[T]) Before ¶
func (c Collection[T]) Before(match func(T) bool) (T, bool)
Before returns the value just before the first for which match returns true. It is false if no value matches, or if the first value does.
Example ¶
Laravel's example of before.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
v, ok := collect.Of(1, 2, 3, 4, 5).Before(func(n int) bool { return n == 3 })
fmt.Println(v, ok)
}
Output: 2 true
func (Collection[T]) Chunk ¶
func (c Collection[T]) Chunk[C interface{ Collection[T] }](size int) Collection[C]
Chunk returns the values in collections of size values each. The last one has fewer if the values run out. It panics with ErrInvalidArgument if size is less than 1, as slices.Chunk panics.
C is always Collection[T], and Go infers it: write c.Chunk(2). See Collection for why it is a type parameter. The result is a Collection like any other, so it chunks again: c.Chunk(2).Chunk(3).
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
chunks := collect.Of(1, 2, 3, 4, 5, 6, 7).Chunk(4)
for chunk := range chunks.Seq() {
fmt.Println(chunk.All())
}
}
Output: [1 2 3 4] [5 6 7]
Example (Nested) ¶
The chunks are a Collection like any other, so they chunk again.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
quads := collect.Of(1, 2, 3, 4, 5, 6, 7, 8).
Chunk(2).
Chunk(2).
Map(func(c collect.Collection[collect.Collection[int]]) [][]int {
return c.Map(collect.Collection[int].All).All()
}).
All()
fmt.Println(quads)
}
Output: [[[1 2] [3 4]] [[5 6] [7 8]]]
func (Collection[T]) ChunkBy ¶
func (c Collection[T]) ChunkBy[K comparable, C interface{ Collection[T] }](f func(T) K) Collection[C]
ChunkBy returns runs of adjacent values that have the same key, as f returns it. C is always Collection[T], and Go infers it.
Example ¶
Laravel's example of chunkBy.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
parity := func(n int) bool { return n%2 == 0 }
chunks := collect.Of(1, 3, 2, 4, 5).ChunkBy(parity)
fmt.Println(chunks.Map(collect.Collection[int].All).All())
}
Output: [[1 3] [2 4] [5]]
func (Collection[T]) ChunkWhile ¶
func (c Collection[T]) ChunkWhile[C interface{ Collection[T] }](keep func(v T, chunk Collection[T]) bool) Collection[C]
ChunkWhile returns runs of values. A run goes on while keep returns true for the next value and the run so far. The run is valid only during the call. C is always Collection[T], and Go infers it, as with Collection.Chunk.
Example ¶
Laravel's example of chunkWhile.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
same := func(letter string, chunk collect.Collection[string]) bool {
last, _ := chunk.Last()
return letter == last
}
chunks := collect.Of("A", "A", "B", "B", "C", "C", "C", "D").ChunkWhile(same)
fmt.Println(chunks.Map(collect.Collection[string].All).All())
}
Output: [[A A] [B B] [C C C] [D]]
func (Collection[T]) Concat ¶
func (c Collection[T]) Concat(others ...Collection[T]) Collection[T]
Concat returns the values of the collection, then of each of others. It is also Laravel's merge of lists.
Example ¶
Laravel's example of concat.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
names := collect.Of("John Doe").
Concat(collect.Of("Jane Doe"), collect.Of("Johnny Doe")).
All()
fmt.Println(names)
}
Output: [John Doe Jane Doe Johnny Doe]
func (Collection[T]) Contains ¶
func (c Collection[T]) Contains(match func(T) bool) bool
Contains reports whether match returns true for a value. It reads no value past that one. To look for a value, compare in match.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 2, 3, 4, 5)
fmt.Println(c.Contains(func(n int) bool { return n > 5 }))
fmt.Println(c.Contains(func(n int) bool { return n == 3 }))
}
Output: false true
func (Collection[T]) Count ¶
func (c Collection[T]) Count() int
Count reads the collection and returns how many values it has.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4).Count())
}
Output: 4
func (Collection[T]) CountBy ¶
func (c Collection[T]) CountBy[K comparable](f func(T) K) KeyedCollection[K, int]
CountBy counts the values by the key f returns for each. The counts are in the order their keys first come. It reads every value before it yields the first count. Pass Identity to count equal values.
Example ¶
Laravel's examples of countBy.
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 2, 2, 3).CountBy(collect.Identity).ToMap())
domain := func(email string) string { return email[strings.Index(email, "@")+1:] }
fmt.Println(collect.Of("alice@gmail.com", "bob@yahoo.com", "carlos@gmail.com").CountBy(domain).ToMap())
}
Output: map[1:1 2:3 3:1] map[gmail.com:2 yahoo.com:1]
func (Collection[T]) CrossJoin ¶
func (c Collection[T]) CrossJoin[U any, Z interface{ Tuple2[T, U] }](other Collection[U]) Collection[Z]
CrossJoin returns each value with each value of other, in order, as a Tuple2. It reads other whole before the first one. An empty other gives none, and reads none of the collection. Z is always Tuple2[T, U], and Go infers it, as with Collection.Chunk.
Example ¶
Laravel's example of crossJoin.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for p := range collect.Of(1, 2).CrossJoin(collect.Of("a", "b")).Seq() {
fmt.Println(p.A, p.B)
}
}
Output: 1 a 1 b 2 a 2 b
func (Collection[T]) DiffBy ¶
func (c Collection[T]) DiffBy[K comparable](other Collection[T], f func(T) K) Collection[T]
DiffBy returns the values whose key, as f returns it, is not the key of a value of other. Pass Identity to compare the values. It reads other whole before the first value.
Example ¶
Laravel's example of diff.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4, 5).DiffBy(collect.Of(2, 4, 6, 8), collect.Identity).All())
}
Output: [1 3 5]
func (Collection[T]) DiffFunc ¶
func (c Collection[T]) DiffFunc(other Collection[T], eq func(a, b T) bool) Collection[T]
DiffFunc returns the values that equal no value of other, as eq tells. It compares each value with each of other, which it reads whole first.
Example ¶
Laravel's diffUsing compares with a function.
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("A", "b", "C").DiffFunc(collect.Of("a", "c"), strings.EqualFold).All())
}
Output: [b]
func (Collection[T]) DoesntContain ¶
func (c Collection[T]) DoesntContain(match func(T) bool) bool
DoesntContain reports whether match returns false for every value.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 2, 3, 4, 5)
fmt.Println(c.DoesntContain(func(n int) bool { return n < 5 }))
}
Output: false
func (Collection[T]) DuplicatesBy ¶
func (c Collection[T]) DuplicatesBy[K comparable](f func(T) K) Collection[K]
DuplicatesBy returns what f returns for each value, each time it returns what it returned for a value before, as Laravel's duplicates does. Pass Identity for the repeated values themselves.
Example ¶
Laravel's example of duplicates.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "a", "c", "b").DuplicatesBy(collect.Identity).All())
}
Output: [a b]
func (Collection[T]) Each ¶
func (c Collection[T]) Each(f func(T))
Each calls f with each value, in order. To stop early, range over Collection.Seq and break.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
collect.Of("a", "b").Each(func(s string) { fmt.Println(s) })
}
Output: a b
func (Collection[T]) Eager ¶
func (c Collection[T]) Eager() Collection[T]
Eager reads every value now, and returns a collection of them. The new collection can be read any number of times, as one from Of can.
Example ¶
Eager reads a source that can be read only once, and the result can be read any number of times.
c := once(1, 2).Eager() fmt.Println(c.All(), c.All())
Output: [1 2] [1 2]
func (Collection[T]) Ensure ¶
func (c Collection[T]) Ensure[U any]() (Collection[U], error)
Ensure reads every value now, and returns them as U. The error wraps ErrUnexpectedValue and names the type of the first value that is not a U. Write U: c.Ensure[*Dog](). It is not lazy: it has to read every value to know there is no error. Collection.MustEnsure is lazy, and panics instead.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
ints, err := collect.Of[any](1, 2).Ensure[int]()
fmt.Println(ints.All(), err)
_, err = collect.Of[any](1, "a").Ensure[int]()
fmt.Println(err)
}
Output: [1 2] <nil> collect: unexpected value: a value of type string is not int
func (Collection[T]) Entries ¶
func (c Collection[T]) Entries[E interface{ Entry[int, T] }]() Collection[E]
Entries returns each value with its index, from 0, as an Entry, as ECMAScript's Array.prototype.entries does. E is always Entry[int, T], and Go infers it, as with Collection.Chunk.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for e := range collect.Of("a", "b").Entries().Seq() {
fmt.Println(e.Key, e.Value)
}
}
Output: 0 a 1 b
func (Collection[T]) Every ¶
func (c Collection[T]) Every(match func(T) bool) bool
Every reports whether match returns true for every value. It is true for an empty collection. It reads no value past the first that fails.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4).Every(func(n int) bool { return n > 2 }))
fmt.Println(collect.Of[int]().Every(func(n int) bool { return n > 2 }))
}
Output: false true
func (Collection[T]) Filter ¶
func (c Collection[T]) Filter(keep func(T) bool) Collection[T]
Filter returns a collection of the values for which keep returns true.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
big := collect.Of(1, 2, 3, 4).
Filter(func(n int) bool { return n > 2 }).
All()
fmt.Println(big)
}
Output: [3 4]
func (Collection[T]) First ¶
func (c Collection[T]) First() (T, bool)
First returns the first value. It is false if there is none. It reads at most one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
v, ok := collect.Of(1, 2, 3).First()
fmt.Println(v, ok)
_, ok = collect.Of[int]().First()
fmt.Println(ok)
}
Output: 1 true false
func (Collection[T]) FirstWhere ¶
func (c Collection[T]) FirstWhere(match func(T) bool) (T, bool)
FirstWhere returns the first value for which match returns true. It is false if there is none. It reads no value past that one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
v, ok := collect.Of(1, 2, 3, 4).FirstWhere(func(n int) bool { return n > 2 })
fmt.Println(v, ok)
}
Output: 3 true
func (Collection[T]) FlatMap ¶
func (c Collection[T]) FlatMap[U any](f func(T) Collection[U]) Collection[U]
FlatMap returns the values of the collections f returns, in order, as one collection. With a function that returns its argument, it flattens a collection of collections, such as the result of Collection.Chunk.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
words := collect.Of("a b", "c").
FlatMap(func(s string) collect.Collection[string] { return collect.FromSlice(strings.Fields(s)) }).
All()
fmt.Println(words)
}
Output: [a b c]
Example (Flatten) ¶
FlatMap with a function that returns its argument flattens chunks.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
flat := collect.Of(1, 2, 3, 4, 5).
Chunk(2).
FlatMap(collect.Identity).
All()
fmt.Println(flat)
}
Output: [1 2 3 4 5]
func (Collection[T]) ForPage ¶
func (c Collection[T]) ForPage(page, perPage int) Collection[T]
ForPage returns the values of page page, from 1, with perPage values to a page. A page before the first is the first. It is Laravel's forPage: Slice(max(0, (page-1)*perPage), perPage), so a negative perPage counts from the end, as Collection.Slice does.
Example ¶
Laravel's example of forPage.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(1, 9).ForPage(2, 3).All())
}
Output: [4 5 6]
func (Collection[T]) GroupBy ¶
func (c Collection[T]) GroupBy[K comparable, C interface{ Collection[T] }](f func(T) K) KeyedCollection[K, C]
GroupBy groups the values by the key f returns for each. The groups are in the order their keys first come. It reads every value before it yields the first group. C is always Collection[T], and Go infers it, as with Collection.Chunk.
Example ¶
Laravel's example of groupBy.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
groups := collect.Of(
account{"account-x10", "Chair"},
account{"account-x10", "Bookcase"},
account{"account-x11", "Desk"},
).GroupBy(func(a account) string { return a.ID })
for id, accounts := range groups.Seq() {
fmt.Println(id, accounts.Map(func(a account) string { return a.Product }).All())
}
}
type account struct {
ID string
Product string
}
Output: account-x10 [Chair Bookcase] account-x11 [Desk]
func (Collection[T]) HasMany ¶
func (c Collection[T]) HasMany() bool
HasMany reports whether the collection has more than one value. It reads at most two, and drops them, as Collection.IsEmpty does. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1).HasMany(), collect.Of(1, 2).HasMany())
}
Output: false true
func (Collection[T]) HasSole ¶
func (c Collection[T]) HasSole() bool
HasSole reports whether the collection has exactly one value. It reads at most two, and drops them, as Collection.IsEmpty does. Filter first to ask about the values that match. Collection.Sole returns the value too. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1).HasSole(), collect.Of(1, 2).HasSole())
// Filter first to ask about the values that match.
fmt.Println(collect.Of(1, 2).Filter(func(n int) bool { return n > 1 }).HasSole())
}
Output: true false true
func (Collection[T]) ImplodeBy ¶
func (c Collection[T]) ImplodeBy[S ~string](f func(T) S, sep string) string
ImplodeBy joins the strings f returns for the values, with sep between them. Pass Identity for a collection of strings.
Example ¶
Laravel's examples of implode.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type product struct{ Name string }
products := collect.Of(product{"Desk"}, product{"Chair"})
fmt.Println(products.ImplodeBy(func(p product) string { return p.Name }, ", "))
fmt.Println(collect.Of("1", "2", "3").ImplodeBy(collect.Identity, "-"))
}
Output: Desk, Chair 1-2-3
func (Collection[T]) IntersectBy ¶
func (c Collection[T]) IntersectBy[K comparable](other Collection[T], f func(T) K) Collection[T]
IntersectBy returns the values whose key, as f returns it, is the key of a value of other. Pass Identity to compare the values. It reads other whole before the first value.
Example ¶
Laravel's example of intersect.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
got := collect.Of("Desk", "Sofa", "Chair").IntersectBy(collect.Of("Desk", "Chair", "Bookcase"), collect.Identity)
fmt.Println(got.All())
}
Output: [Desk Chair]
func (Collection[T]) IntersectFunc ¶
func (c Collection[T]) IntersectFunc(other Collection[T], eq func(a, b T) bool) Collection[T]
IntersectFunc returns the values that equal a value of other, as eq tells. It compares each value with each of other, which it reads whole first.
Example ¶
Laravel's intersectUsing compares with a function.
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("A", "b", "C").IntersectFunc(collect.Of("a", "c"), strings.EqualFold).All())
}
Output: [A C]
func (Collection[T]) IsEmpty ¶
func (c Collection[T]) IsEmpty() bool
IsEmpty reports whether the collection has no values. It reads at most one.
It drops the values it reads. A source that can be read once loses them: call Remember first. A source that runs a query on each read runs it again when the collection is read after.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of[int]().IsEmpty(), collect.Of(1).IsEmpty())
}
Output: true false
Example (Remember) ¶
A source that can be read once loses the value IsEmpty reads, unless Remember keeps it.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
cursor := func() func(func(int) bool) {
used := false
return func(yield func(int) bool) {
if used {
return
}
used = true
for n := 1; n <= 3; n++ {
if !yield(n) {
return
}
}
}
}
once := collect.FromSeq(cursor())
fmt.Println(once.IsEmpty(), once.All()) // false [], the cursor is used up
kept := collect.FromSeq(cursor()).Remember()
fmt.Println(kept.IsEmpty(), kept.All()) // false [1 2 3]
}
Output: false [] false [1 2 3]
func (Collection[T]) IsNotEmpty ¶
func (c Collection[T]) IsNotEmpty() bool
IsNotEmpty reports whether the collection has a value. It reads at most one, and drops it, as Collection.IsEmpty does. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of[int]().IsNotEmpty(), collect.Of(1).IsNotEmpty())
}
Output: false true
func (Collection[T]) JoinBy ¶
func (c Collection[T]) JoinBy[S ~string](f func(T) S, sep string) string
JoinBy is Collection.ImplodeBy, under the name of strings.Join. For Laravel's join with a final glue, see Collection.JoinFinalBy.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c").JoinBy(collect.Identity, "/"))
}
Output: a/b/c
func (Collection[T]) JoinFinalBy ¶
func (c Collection[T]) JoinFinalBy[S ~string](f func(T) S, glue, finalGlue string) string
JoinFinalBy joins the strings f returns for the values, with glue between them and finalGlue before the last, as in "a, b and c". It is Laravel's join with a final glue. An empty finalGlue is glue. Pass Identity for a collection of strings.
Example ¶
Laravel's examples of join, with a final glue.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c").JoinFinalBy(collect.Identity, ", ", " and "))
fmt.Println(collect.Of("a", "b").JoinFinalBy(collect.Identity, ", ", " and "))
fmt.Println(collect.Of("a").JoinFinalBy(collect.Identity, ", ", " and "))
}
Output: a, b and c a and b a
func (Collection[T]) KeyBy ¶
func (c Collection[T]) KeyBy[K comparable](f func(T) K) KeyedCollection[K, T]
KeyBy returns the values with f(v) as the key of each v.
Example ¶
Laravel's example of keyBy.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type product struct {
ID string
Name string
}
byID := collect.Of(product{"prod-100", "Desk"}, product{"prod-200", "Chair"}).
KeyBy(func(p product) string { return p.ID })
for id, p := range byID.Seq() {
fmt.Println(id, p.Name)
}
}
Output: prod-100 Desk prod-200 Chair
func (Collection[T]) Keyed ¶
func (c Collection[T]) Keyed() KeyedCollection[int, T]
Keyed returns the values with their indexes, from 0, as keys.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for k, v := range collect.Of("a", "b", "c").Keyed().Seq() {
fmt.Println(k, v)
}
}
Output: 0 a 1 b 2 c
func (Collection[T]) Last ¶
func (c Collection[T]) Last() (T, bool)
Last returns the last value. It is false if there is none. It reads every value.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
v, ok := collect.Of(1, 2, 3, 4).Last()
fmt.Println(v, ok)
}
Output: 4 true
func (Collection[T]) Map ¶
func (c Collection[T]) Map[U any](f func(T) U) Collection[U]
Map returns a collection of f applied to each value.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
doubled := collect.Of(1, 2, 3, 4, 5).
Map(func(n int) int { return n * 2 }).
All()
fmt.Println(doubled)
}
Output: [2 4 6 8 10]
Example (NewType) ¶
Map can change the type of the values in the middle of a chain.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
labels := collect.Of(1, 2).
Map(func(n int) string { return fmt.Sprintf("#%d", n) }).
All()
fmt.Println(labels)
}
Output: [#1 #2]
func (Collection[T]) MapToGroups ¶
func (c Collection[T]) MapToGroups[K comparable, U any](f func(T) (K, U)) KeyedCollection[K, Collection[U]]
MapToGroups groups the values f returns by the keys it returns with them. The groups are in the order their keys first come. It reads every value before it yields the first group. Laravel's mapToDictionary is the same in Go.
Example ¶
Laravel's example of mapToGroups.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
groups := collect.Of(
employee{"John Doe", "Sales"},
employee{"Jane Doe", "Sales"},
employee{"Johnny Doe", "Marketing"},
).MapToGroups(func(e employee) (string, string) { return e.Department, e.Name })
for department, names := range groups.Seq() {
fmt.Println(department, names.All())
}
}
type employee struct{ Name, Department string }
Output: Sales [John Doe Jane Doe] Marketing [Johnny Doe]
func (Collection[T]) MapWithKeys ¶
func (c Collection[T]) MapWithKeys[K comparable, U any](f func(T) (K, U)) KeyedCollection[K, U]
MapWithKeys returns the key and value f returns for each value.
Example ¶
Laravel's example of mapWithKeys.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type person struct{ Name, Department, Email string }
byEmail := collect.Of(
person{"John", "Sales", "john@example.com"},
person{"Jane", "Marketing", "jane@example.com"},
).MapWithKeys(func(p person) (string, string) { return p.Email, p.Name })
fmt.Println(byEmail.ToMap())
}
Output: map[jane@example.com:Jane john@example.com:John]
func (Collection[T]) MarshalJSONTo ¶
func (c Collection[T]) MarshalJSONTo(enc *jsontext.Encoder) error
MarshalJSONTo writes the values to enc as a JSON array, as each is read. It stands for Laravel's toJson. json.Marshal calls it, with enc's options, in encoding/json/v2 and in encoding/json.
Example ¶
b, err := jsonv2.Marshal(collect.Of(user{"Alice", 31}, user{"Bob", 19}))
fmt.Println(string(b), err)
Output: [{"Name":"Alice","Age":31},{"Name":"Bob","Age":19}] <nil>
func (Collection[T]) MaxBy ¶
func (c Collection[T]) MaxBy[K cmp.Ordered](f func(T) K) (K, bool)
MaxBy returns the greatest of the keys f returns for the values, as Laravel's max returns it: the key, not the value. For the value itself, use SortByDesc(f).First(). It is false for an empty collection. Pass Identity for a collection of keys.
Example ¶
Laravel's examples of max.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type score struct{ Foo int }
greatest, ok := collect.Of(score{10}, score{20}).MaxBy(func(s score) int { return s.Foo })
fmt.Println(greatest, ok)
greatest, ok = collect.Of(1, 2, 3, 4, 5).MaxBy(collect.Identity)
fmt.Println(greatest, ok)
}
Output: 20 true 5 true
func (Collection[T]) MedianBy ¶
func (c Collection[T]) MedianBy[N Number](f func(T) N) (float64, bool)
MedianBy returns the middle of the numbers f returns for the values, or the mean of the two middle ones. It is false for an empty collection. It keeps every number. Pass Identity for a collection of numbers.
Example ¶
Laravel's examples of median.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type score struct{ Foo int }
median, ok := collect.Of(score{10}, score{10}, score{20}, score{40}).MedianBy(func(s score) int { return s.Foo })
fmt.Println(median, ok)
median, ok = collect.Of(1, 1, 2, 4).MedianBy(collect.Identity)
fmt.Println(median, ok)
}
Output: 15 true 1.5 true
func (Collection[T]) MinBy ¶
func (c Collection[T]) MinBy[K cmp.Ordered](f func(T) K) (K, bool)
MinBy returns the least of the keys f returns for the values, as Laravel's min returns it: the key, not the value. For the value itself, use SortBy(f).First(). It is false for an empty collection. Pass Identity for a collection of keys.
Example ¶
Laravel's examples of min.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type score struct{ Foo int }
least, ok := collect.Of(score{10}, score{20}).MinBy(func(s score) int { return s.Foo })
fmt.Println(least, ok)
least, ok = collect.Of(1, 2, 3, 4, 5).MinBy(collect.Identity)
fmt.Println(least, ok)
}
Output: 10 true 1 true
func (Collection[T]) ModeBy ¶
func (c Collection[T]) ModeBy[K comparable](f func(T) K) Collection[K]
ModeBy returns the keys that f returns most often for the values, in the order they first come. It is empty for an empty collection. It reads every value before it yields the first key. Pass Identity for a collection of keys.
Example ¶
Laravel's examples of mode.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type score struct{ Foo int }
fmt.Println(collect.Of(score{10}, score{10}, score{20}, score{40}).ModeBy(func(s score) int { return s.Foo }).All())
fmt.Println(collect.Of(1, 1, 2, 4).ModeBy(collect.Identity).All())
fmt.Println(collect.Of(1, 1, 2, 2).ModeBy(collect.Identity).All())
}
Output: [10] [1] [1 2]
func (Collection[T]) Multiply ¶
func (c Collection[T]) Multiply(n int) Collection[T]
Multiply returns the values n times over. Each read reads the collection once, as Laravel's multiply does, and repeats what it read. A negative n is 0.
Example ¶
Laravel's example of multiply.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b").Multiply(3).All())
}
Output: [a b a b a b]
func (Collection[T]) MustEnsure ¶
func (c Collection[T]) MustEnsure[U any]() Collection[U]
MustEnsure returns the values as U, lazily. Write U: c.MustEnsure[*Dog](). Reading a value that is not a U panics with the error Collection.Ensure would return, which wraps ErrUnexpectedValue, as Laravel's ensure throws.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
defer func() { fmt.Println("panic:", recover()) }()
for n := range collect.Of[any](1, "a").MustEnsure[int]().Seq() {
fmt.Println(n)
}
}
Output: 1 panic: collect: unexpected value: a value of type string is not int
func (Collection[T]) MustFirst ¶
func (c Collection[T]) MustFirst() T
MustFirst returns the first value. It panics with ErrItemNotFound if there is none, as Laravel's firstOrFail throws. It reads at most one. Collection.First reports the absence instead.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3).MustFirst())
defer func() { fmt.Println("panic:", recover()) }()
collect.Of[int]().MustFirst()
}
Output: 1 panic: collect: item not found
func (Collection[T]) MustLast ¶
func (c Collection[T]) MustLast() T
MustLast returns the last value. It panics with ErrItemNotFound if there is none. It reads every value. Collection.Last reports the absence instead.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3).MustLast())
}
Output: 3
func (Collection[T]) MustSole ¶
func (c Collection[T]) MustSole() T
MustSole returns the only value. It panics with the error Collection.Sole would return, ErrItemNotFound or ErrMultipleItemsFound, as Laravel's sole throws. It reads at most two.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3).Filter(func(n int) bool { return n == 2 }).MustSole())
defer func() { fmt.Println("panic:", recover()) }()
collect.Of(1, 2, 3).MustSole()
}
Output: 2 panic: collect: multiple items found
func (Collection[T]) Nth ¶
func (c Collection[T]) Nth(step, offset int) Collection[T]
Nth returns every step-th value, starting at offset. A negative offset counts from the end. It panics with ErrInvalidArgument if step is less than 1, as Laravel throws.
Example ¶
Laravel's examples of nth.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("a", "b", "c", "d", "e", "f")
fmt.Println(c.Nth(4, 0).All())
fmt.Println(c.Nth(4, 1).All())
}
Output: [a e] [b f]
func (Collection[T]) Pad ¶
func (c Collection[T]) Pad(size int, v T) Collection[T]
Pad returns the values, then copies of v until there are size values. A negative size puts the copies before the values, until there are -size, and reads every value first.
Example ¶
Laravel's examples of pad.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("A", "B", "C")
fmt.Println(c.Pad(5, "0").All())
fmt.Println(c.Pad(-5, "0").All())
}
Output: [A B C 0 0] [0 0 A B C]
func (Collection[T]) Partition ¶
func (c Collection[T]) Partition(match func(T) bool) (Collection[T], Collection[T])
Partition returns the values for which match returns true, and those for which it returns false. It reads the collection once, when either result is first read, and keeps both, as Laravel's partition reads once. Later reads of either return the kept values.
If match or the source panics, nothing is kept, and the next read starts again. match must not read either result: it would wait for itself.
Example ¶
Laravel's example of partition.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
under3, over3 := collect.Of(1, 2, 3, 4, 5, 6).Partition(func(n int) bool { return n < 3 })
fmt.Println(under3.All(), over3.All())
}
Output: [1 2] [3 4 5 6]
func (Collection[T]) Percentage ¶
func (c Collection[T]) Percentage(match func(T) bool, precision int) (float64, bool)
Percentage returns the percentage of the values for which match returns true, rounded to precision decimal places. It is false for an empty collection.
Example ¶
Laravel's examples of percentage.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 1, 2, 2, 2, 3)
one := func(n int) bool { return n == 1 }
fmt.Println(c.Percentage(one, 2))
fmt.Println(c.Percentage(one, 3))
}
Output: 33.33 true 33.333 true
func (Collection[T]) Pipe ¶
func (c Collection[T]) Pipe[U any](f func(Collection[T]) U) U
Pipe returns what f returns for the collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
total := collect.Of(1, 2, 3).Pipe(func(c collect.Collection[int]) int { return c.SumBy(collect.Identity) })
fmt.Println(total)
}
Output: 6
func (Collection[T]) PipeThrough ¶
func (c Collection[T]) PipeThrough(fs ...func(Collection[T]) Collection[T]) Collection[T]
PipeThrough passes the collection through each of fs in turn, and returns what the last returns.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
more := func(c collect.Collection[int]) collect.Collection[int] { return c.Concat(collect.Of(4, 5)) }
double := func(c collect.Collection[int]) collect.Collection[int] {
return c.Map(func(n int) int { return n * 2 })
}
fmt.Println(collect.Of(1, 2, 3).PipeThrough(more, double).All())
}
Output: [2 4 6 8 10]
func (Collection[T]) Random ¶
func (c Collection[T]) Random() (T, bool)
Random returns a value chosen at random. It is false for an empty collection, where Laravel's random throws. It reads every value, and keeps only one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
n, ok := collect.Range(1, 5).Random()
fmt.Println(n >= 1 && n <= 5, ok)
}
Output: true true
func (Collection[T]) RandomN ¶
func (c Collection[T]) RandomN(n int) (Collection[T], error)
RandomN reads every value now, and returns n of them chosen at random, in the order they come. The error wraps ErrNotEnoughItems if there are fewer than n. A negative n is 0, as in Laravel.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c, err := collect.Range(1, 5).RandomN(3)
fmt.Println(c.Count(), err)
_, err = collect.Range(1, 5).RandomN(6)
fmt.Println(err)
}
Output: 3 <nil> collect: not enough items: asked for 6, but there are only 5
func (Collection[T]) Reduce ¶
func (c Collection[T]) Reduce[A any](f func(A, T) A, initial A) A
Reduce returns f applied to the result so far and each value in turn, starting from initial. The arguments are in Laravel's order.
Example ¶
Laravel's example of reduce.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
total := collect.Of(1, 2, 3).Reduce(func(carry, n int) int { return carry + n }, 4)
fmt.Println(total)
}
Output: 10
func (Collection[T]) Reject ¶
func (c Collection[T]) Reject(drop func(T) bool) Collection[T]
Reject returns a collection of the values for which drop returns false.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
small := collect.Of(1, 2, 3, 4).
Reject(func(n int) bool { return n > 2 }).
All()
fmt.Println(small)
}
Output: [1 2]
func (Collection[T]) Remember ¶
func (c Collection[T]) Remember() Collection[T]
Remember returns a collection that reads the source once, and keeps each value it reads. A later read gets the kept values first, then reads on from where the source stopped. So a source that can be read only once can be read again.
It is not safe for concurrent reads. The source stays open between reads until it ends, or until the collection is garbage collected; a source that refers to the collection keeps it alive, and stays open. If the source panics, every later read past the kept values panics the same way. The source must not read the collection past the kept values: that panics too, as iter.Pull does.
Example ¶
Remember reads the source once. A later read gets the kept values, then reads on.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Range(1, 5).
TapEach(func(n int) { fmt.Println("read", n) }).
Remember()
fmt.Println(c.Take(2).All())
fmt.Println(c.Take(3).All())
}
Output: read 1 read 2 [1 2] read 3 [1 2 3]
func (Collection[T]) Reverse ¶
func (c Collection[T]) Reverse() Collection[T]
Reverse returns the values last first. It reads every value before the first.
Example ¶
Laravel's example of reverse.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c", "d", "e").Reverse().All())
}
Output: [e d c b a]
func (Collection[T]) Search ¶
func (c Collection[T]) Search(match func(T) bool) (int, bool)
Search returns the index, from 0, of the first value for which match returns true. It is false if there is none. It reads the values in order, as slices.IndexFunc does: it is not a binary search.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
i, ok := collect.Of(2, 4, 6, 8).Search(func(n int) bool { return n == 4 })
fmt.Println(i, ok)
}
Output: 1 true
func (Collection[T]) Seq ¶
func (c Collection[T]) Seq() iter.Seq[T]
Seq returns the sequence of the collection, for a range loop or for the iter, slices and maps packages.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for v := range collect.Of("a", "b").Seq() {
fmt.Println(v)
}
}
Output: a b
func (Collection[T]) Shuffle ¶
func (c Collection[T]) Shuffle() Collection[T]
Shuffle returns the values in a random order, new on each read. It reads every value before the first.
Example ¶
The order is random, so the example shows what does not change.
package main
import (
"fmt"
"slices"
"github.com/mpyw/collect"
)
func main() {
shuffled := collect.Range(1, 5).Shuffle().All()
slices.Sort(shuffled)
fmt.Println(shuffled)
}
Output: [1 2 3 4 5]
func (Collection[T]) Skip ¶
func (c Collection[T]) Skip(n int) Collection[T]
Skip returns a collection of the values after the first n. A negative n is 0.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(1, 10).Skip(4).All())
}
Output: [5 6 7 8 9 10]
func (Collection[T]) SkipUntil ¶
func (c Collection[T]) SkipUntil(match func(T) bool) Collection[T]
SkipUntil returns the values from the first for which match returns true.
Example ¶
Laravel's example of skipUntil.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4).SkipUntil(func(n int) bool { return n >= 3 }).All())
}
Output: [3 4]
func (Collection[T]) SkipWhile ¶
func (c Collection[T]) SkipWhile(match func(T) bool) Collection[T]
SkipWhile returns the values from the first for which match returns false.
Example ¶
Laravel's example of skipWhile.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4).SkipWhile(func(n int) bool { return n <= 3 }).All())
}
Output: [4]
func (Collection[T]) Slice ¶
func (c Collection[T]) Slice(offset, length int) Collection[T]
Slice returns length values from offset, as PHP's array_slice does. A negative offset counts from the end. A negative length stops that many values before the end. With both non-negative it is Skip(offset). Take(length), and lazy. Otherwise it reads every value.
Example ¶
Laravel's examples of slice, and PHP's array_slice with negative values.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Range(1, 10)
fmt.Println(c.Slice(4, 2).All())
fmt.Println(c.Slice(-3, 2).All())
fmt.Println(c.Slice(2, -3).All())
}
Output: [5 6] [8 9] [3 4 5 6 7]
func (Collection[T]) Sliding ¶
func (c Collection[T]) Sliding[C interface{ Collection[T] }](size, step int) Collection[C]
Sliding returns windows of size values, each step values after the one before. Only full windows are returned. It panics with ErrInvalidArgument if size or step is less than 1, as Laravel throws. C is always Collection[T], and Go infers it.
Example ¶
Laravel's examples of sliding.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
all := collect.Collection[int].All
fmt.Println(collect.Range(1, 5).Sliding(2, 1).Map(all).All())
fmt.Println(collect.Range(1, 5).Sliding(3, 2).Map(all).All())
}
Output: [[1 2] [2 3] [3 4] [4 5]] [[1 2 3] [3 4 5]]
func (Collection[T]) Sole ¶
func (c Collection[T]) Sole() (T, error)
Sole returns the only value. The error is ErrItemNotFound if there is none, and ErrMultipleItemsFound if there is more than one. It reads at most two. Filter first for the only value that matches.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/mpyw/collect"
)
func main() {
v, err := collect.Of(1, 2, 3).Filter(func(n int) bool { return n == 2 }).Sole()
fmt.Println(v, err)
_, err = collect.Of(1, 2, 3).Sole()
fmt.Println(errors.Is(err, collect.ErrMultipleItemsFound))
}
Output: 2 <nil> true
func (Collection[T]) SortBy ¶
func (c Collection[T]) SortBy[K cmp.Ordered](f func(T) K) Collection[T]
SortBy returns the values sorted by the key f returns for each, least first. Equal keys keep their order. Pass Identity for Laravel's sort. It reads every value before the first.
Example ¶
Laravel's examples of sort and sortBy.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(5, 3, 1, 2, 4).SortBy(collect.Identity).All())
type product struct {
Name string
Price int
}
products := collect.Of(product{"Desk", 200}, product{"Chair", 100}, product{"Bookcase", 150})
fmt.Println(products.SortBy(func(p product) int { return p.Price }).All())
}
Output: [1 2 3 4 5] [{Chair 100} {Bookcase 150} {Desk 200}]
func (Collection[T]) SortByDesc ¶
func (c Collection[T]) SortByDesc[K cmp.Ordered](f func(T) K) Collection[T]
SortByDesc returns the values sorted by the key f returns for each, greatest first. Equal keys keep their order. Pass Identity for Laravel's sortDesc. It reads every value before the first.
Example ¶
Laravel's sortDesc and sortByDesc.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(5, 3, 1, 2, 4).SortByDesc(collect.Identity).All())
}
Output: [5 4 3 2 1]
func (Collection[T]) SortFunc ¶
func (c Collection[T]) SortFunc(cmp func(a, b T) int) Collection[T]
SortFunc returns the values sorted by cmp, which returns a negative number, zero or a positive number, as cmp.Compare does. Equal values keep their order. It reads every value before the first.
Example ¶
Laravel's sort with a callback. Equal values keep their order.
package main
import (
"cmp"
"fmt"
"github.com/mpyw/collect"
)
func main() {
byLength := func(a, b string) int { return cmp.Compare(len(a), len(b)) }
fmt.Println(collect.Of("ccc", "a", "bb", "d").SortFunc(byLength).All())
}
Output: [a d bb ccc]
func (Collection[T]) Split ¶
func (c Collection[T]) Split[C interface{ Collection[T] }](n int) Collection[C]
Split returns the values in n groups, as even in size as can be. The first groups have one more value when they cannot all be the same. There are fewer than n groups if there are fewer than n values. It reads every value first, and panics with ErrInvalidArgument if n is less than 1. C is always Collection[T], and Go infers it.
Example ¶
Laravel's example of split: the groups are as even as can be.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(1, 5).Split(3).Map(collect.Collection[int].All).All())
}
Output: [[1 2] [3 4] [5]]
func (Collection[T]) SplitIn ¶
func (c Collection[T]) SplitIn[C interface{ Collection[T] }](n int) Collection[C]
SplitIn returns the values in n groups, each full but the last, as Laravel's splitIn does. It reads every value first, and panics with ErrInvalidArgument if n is less than 1. C is always Collection[T], and Go infers it.
Example ¶
Laravel's example of splitIn: each group is full but the last.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(1, 10).SplitIn(3).Map(collect.Collection[int].All).All())
}
Output: [[1 2 3 4] [5 6 7 8] [9 10]]
func (Collection[T]) SumBy ¶
func (c Collection[T]) SumBy[N Number](f func(T) N) N
SumBy returns the sum of the numbers f returns for the values. Pass Identity for a collection of numbers.
Example ¶
Laravel's examples of sum.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
type book struct {
Name string
Pages int
}
books := collect.Of(book{"JavaScript: The Good Parts", 176}, book{"JavaScript: The Definitive Guide", 1096})
fmt.Println(collect.Of(1, 2, 3, 4, 5).SumBy(collect.Identity))
fmt.Println(books.SumBy(func(b book) int { return b.Pages }))
}
Output: 15 1272
func (Collection[T]) Take ¶
func (c Collection[T]) Take(n int) Collection[T]
Take returns a collection of the first n values, or of all of them if there are fewer. It reads no value past the nth, so it ends an endless sequence.
A negative n takes the last -n values instead, as Laravel does. Those are known only at the end, so it reads every value, and keeps -n of them.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Range(0, 5)
fmt.Println(c.Take(3).All())
fmt.Println(c.Take(-2).All()) // The last 2, as in Laravel.
}
Output: [0 1 2] [4 5]
func (Collection[T]) TakeUntil ¶
func (c Collection[T]) TakeUntil(match func(T) bool) Collection[T]
TakeUntil returns the values before the first for which match returns true. It reads no value past that one.
Example ¶
Laravel's example of takeUntil.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4).TakeUntil(func(n int) bool { return n >= 3 }).All())
}
Output: [1 2]
func (Collection[T]) TakeWhile ¶
func (c Collection[T]) TakeWhile(match func(T) bool) Collection[T]
TakeWhile returns the values up to the first for which match returns false. It reads no value past that one.
Example ¶
Laravel's example of takeWhile.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 2, 3, 4).TakeWhile(func(n int) bool { return n < 3 }).All())
}
Output: [1 2]
func (Collection[T]) TapEach ¶
func (c Collection[T]) TapEach(f func(T)) Collection[T]
TapEach returns the same values, calling f with each as it is read.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
firstTwo := collect.Of(1, 2, 3, 4).
TapEach(func(n int) { fmt.Println("read", n) }).
Take(2).
All()
fmt.Println(firstTwo)
}
Output: read 1 read 2 [1 2]
func (Collection[T]) UniqueBy ¶
func (c Collection[T]) UniqueBy[K comparable](f func(T) K) Collection[T]
UniqueBy returns the first value of each key, as f returns it. Pass Identity to drop equal values. It keeps every key it has seen.
Example ¶
Laravel's examples of unique.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of(1, 1, 2, 2, 3, 4, 2).UniqueBy(collect.Identity).All())
type product struct{ Name, Brand string }
products := collect.Of(product{"iPhone 6", "Apple"}, product{"iPhone 5", "Apple"}, product{"Galaxy S6", "Samsung"})
fmt.Println(products.UniqueBy(func(p product) string { return p.Brand }).All())
}
Output: [1 2 3 4] [{iPhone 6 Apple} {Galaxy S6 Samsung}]
func (Collection[T]) Unless ¶
func (c Collection[T]) Unless(cond bool, f func(Collection[T]) Collection[T]) Collection[T]
Unless returns f applied to the collection if cond is false, and the collection itself if not.
Example ¶
Laravel's example of unless.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
addFour := func(c collect.Collection[int]) collect.Collection[int] { return c.Concat(collect.Of(4)) }
fmt.Println(collect.Of(1, 2, 3).Unless(true, addFour).All())
fmt.Println(collect.Of(1, 2, 3).Unless(false, addFour).All())
}
Output: [1 2 3] [1 2 3 4]
func (Collection[T]) When ¶
func (c Collection[T]) When(cond bool, f func(Collection[T]) Collection[T]) Collection[T]
When returns f applied to the collection if cond is true, and the collection itself if not. It keeps a chain going through a condition.
Example ¶
Laravel's example of when.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
addFour := func(c collect.Collection[int]) collect.Collection[int] { return c.Concat(collect.Of(4)) }
fmt.Println(collect.Of(1, 2, 3).When(true, addFour).All())
fmt.Println(collect.Of(1, 2, 3).When(false, addFour).All())
}
Output: [1 2 3 4] [1 2 3]
func (Collection[T]) WhereBetweenBy ¶
func (c Collection[T]) WhereBetweenBy[K cmp.Ordered](f func(T) K, low, high K) Collection[T]
WhereBetweenBy returns the values whose key, as f returns it, is from low to high, both included.
Example ¶
Laravel's example of whereBetween.
products := collect.Of(
priced{"Desk", 200},
priced{"Chair", 80},
priced{"Bookcase", 150},
priced{"Pencil", 30},
priced{"Door", 100},
)
price := func(p priced) int { return p.Price }
fmt.Println(products.WhereBetweenBy(price, 100, 200).All())
Output: [{Desk 200} {Bookcase 150} {Door 100}]
func (Collection[T]) WhereInBy ¶
func (c Collection[T]) WhereInBy[K comparable](f func(T) K, keys ...K) Collection[T]
WhereInBy returns the values whose key, as f returns it, is one of keys.
Example ¶
Laravel's example of whereIn.
products := collect.Of(
priced{"Desk", 200},
priced{"Chair", 100},
priced{"Bookcase", 150},
priced{"Door", 100},
)
price := func(p priced) int { return p.Price }
fmt.Println(products.WhereInBy(price, 150, 200).All())
Output: [{Desk 200} {Bookcase 150}]
func (Collection[T]) WhereInstanceOf ¶
func (c Collection[T]) WhereInstanceOf[U any]() Collection[U]
WhereInstanceOf returns the values that are of type U, as U. Write U: c.WhereInstanceOf[*Dog](). An interface U keeps the values that implement it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
values := collect.Of[any](1, "a", 2, square(3))
fmt.Println(values.WhereInstanceOf[int]().All())
fmt.Println(values.WhereInstanceOf[shape]().Map(shape.area).All())
}
type shape interface{ area() int }
type square int
func (s square) area() int { return int(s * s) }
Output: [1 2] [9]
func (Collection[T]) WhereNotBetweenBy ¶
func (c Collection[T]) WhereNotBetweenBy[K cmp.Ordered](f func(T) K, low, high K) Collection[T]
WhereNotBetweenBy returns the values whose key, as f returns it, is below low or above high.
Example ¶
Laravel's example of whereNotBetween.
products := collect.Of(
priced{"Desk", 200},
priced{"Chair", 80},
priced{"Bookcase", 150},
priced{"Pencil", 30},
priced{"Door", 100},
)
price := func(p priced) int { return p.Price }
fmt.Println(products.WhereNotBetweenBy(price, 100, 200).All())
Output: [{Chair 80} {Pencil 30}]
func (Collection[T]) WhereNotInBy ¶
func (c Collection[T]) WhereNotInBy[K comparable](f func(T) K, keys ...K) Collection[T]
WhereNotInBy returns the values whose key, as f returns it, is none of keys.
Example ¶
Laravel's example of whereNotIn.
products := collect.Of(
priced{"Desk", 200},
priced{"Chair", 100},
priced{"Bookcase", 150},
priced{"Door", 100},
)
price := func(p priced) int { return p.Price }
fmt.Println(products.WhereNotInBy(price, 150, 200).All())
Output: [{Chair 100} {Door 100}]
func (Collection[T]) Zip2 ¶
func (c Collection[T]) Zip2[U any, Z interface{ Tuple2[T, U] }](other Collection[U]) Collection[Z]
Zip2 returns each value with the value of other at the same place, as a Tuple2: A is the value, and B is other's. It goes on to the end of the longer one, as Laravel does: the missing side is the zero value. Z is always Tuple2[T, U], and Go infers it, as with Collection.Chunk. Collection.Zip3, Collection.Zip4 and Collection.Zip5 zip more.
Example ¶
Laravel's example of zip.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for p := range collect.Of("Chair", "Desk").Zip2(collect.Of(100, 200)).Seq() {
fmt.Println(p.A, p.B)
}
}
Output: Chair 100 Desk 200
func (Collection[T]) Zip3 ¶
func (c Collection[T]) Zip3[U, V any, Z interface{ Tuple3[T, U, V] }](us Collection[U], vs Collection[V]) Collection[Z]
Zip3 returns each value with the values of us and vs at the same place, as a Tuple3, as Collection.Zip2 does for two collections. It goes on to the end of the longest of the three: a missing value is the zero value. Z is always Tuple3[T, U, V], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
names := collect.Of("Chair", "Desk")
prices := collect.Of(100, 200)
stock := collect.Of(true, false)
for t := range names.Zip3(prices, stock).Seq() {
fmt.Println(t.A, t.B, t.C)
}
}
Output: Chair 100 true Desk 200 false
func (Collection[T]) Zip4 ¶
func (c Collection[T]) Zip4[U, V, W any, Z interface{ Tuple4[T, U, V, W] }](us Collection[U], vs Collection[V], ws Collection[W]) Collection[Z]
Zip4 returns each value with the values of us, vs and ws at the same place, as a Tuple4, as Collection.Zip2 does for two collections. It goes on to the end of the longest of the four: a missing value is the zero value. Z is always Tuple4[T, U, V, W], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
t := collect.Of(1).Zip4(collect.Of("a"), collect.Of(true), collect.Of(1.5)).MustFirst()
fmt.Println(t.A, t.B, t.C, t.D)
}
Output: 1 a true 1.5
func (Collection[T]) Zip5 ¶
func (c Collection[T]) Zip5[U, V, W, X any, Z interface{ Tuple5[T, U, V, W, X] }](us Collection[U], vs Collection[V], ws Collection[W], xs Collection[X]) Collection[Z]
Zip5 returns each value with the values of us, vs, ws and xs at the same place, as a Tuple5, as Collection.Zip2 does for two collections. It goes on to the end of the longest of the five: a missing value is the zero value. Z is always Tuple5[T, U, V, W, X], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
t := collect.Of(1).Zip5(collect.Of("a"), collect.Of(true), collect.Of(1.5), collect.Of('x')).MustFirst()
fmt.Println(t.A, t.B, t.C, t.D, string(t.E))
}
Output: 1 a true 1.5 x
type Entry ¶
type Entry[K, V any] struct { Key K Value V }
Entry holds a key and its value, as an entry of an ECMAScript Map does. KeyedCollection.Entries returns the entries of a keyed collection, and Collection.Entries those of a collection with its indexes as keys.
func E ¶
E returns an Entry of k and v. Go infers their types, which a literal such as Entry[int, string]{1, "a"} spells out, and go vet asks the fields of a literal from another package to be named.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.E("a", 1))
}
Output: {a 1}
type KeyedCollection ¶
type KeyedCollection[K comparable, V any] struct { // contains filtered or unexported fields }
KeyedCollection is a lazy sequence of values of type V, each with a key of type K. Collection.Keyed and Collection.KeyBy return it, and KeyedCollection.Values turns it back into a Collection.
FromSeq2 and FromMap make one from the standard library's types.
It is a sequence of pairs, not a map: a key may come more than once. Only KeyedCollection.ToMap collapses them, as a map does.
func Combine ¶
func Combine[K comparable, V any](keys Collection[K], values Collection[V]) (KeyedCollection[K, V], error)
Combine reads both now, and returns the keys, each with the value of values at the same place. The error wraps ErrLengthMismatch if there are not as many values as keys. It is not lazy: it has to read both to know there is no error. MustCombine is lazy, and panics instead.
Example ¶
Laravel's example of combine.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c, err := collect.Combine(collect.Of("name", "age"), collect.Of[any]("George", 29))
fmt.Println(c.ToMap(), err)
_, err = collect.Combine(collect.Of("name", "age"), collect.Of[any]("George"))
fmt.Println(err)
}
Output: map[age:29 name:George] <nil> collect: lengths do not match: 2 keys and 1 values
func FromEntries ¶
func FromEntries[K comparable, V any](c Collection[Entry[K, V]]) KeyedCollection[K, V]
FromEntries returns a keyed collection of the entries of c, each Key with its Value. It undoes KeyedCollection.Entries: FromEntries(k.Entries()) reads the same pairs as k.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
entries := collect.Of(collect.E("a", 1), collect.E("b", 2))
fmt.Println(collect.FromEntries(entries).ToMap())
}
Output: map[a:1 b:2]
func FromMap ¶
func FromMap[K comparable, V any](m map[K]V) KeyedCollection[K, V]
FromMap returns a keyed collection that reads m, with no copy. As with range over a map, the order of the pairs is not specified, and differs from one read to the next.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"apple": 3, "banana": 5})
fmt.Println(c.Values().SumBy(collect.Identity), c.Count())
}
Output: 8 2
func FromSeq2 ¶
func FromSeq2[K comparable, V any](seq iter.Seq2[K, V]) KeyedCollection[K, V]
FromSeq2 returns a keyed collection that reads seq. A nil seq is empty.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromSeq2(slices.All([]string{"a", "b"}))
for k, v := range c.Seq() {
fmt.Println(k, v)
}
}
Output: 0 a 1 b
func MustCombine ¶
func MustCombine[K comparable, V any](keys Collection[K], values Collection[V]) KeyedCollection[K, V]
MustCombine returns the keys, each with the value of values at the same place, lazily. Reading it panics with an error that wraps ErrLengthMismatch once one runs out before the other, as Laravel's combine throws.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.MustCombine(collect.Of("a", "b"), collect.Range(1, 2)).ToMap())
}
Output: map[a:1 b:2]
func (KeyedCollection[K, V]) After ¶
func (c KeyedCollection[K, V]) After(match func(K, V) bool) (K, V, bool)
After returns the pair just after the first for which match returns true. It is false if no pair matches, or if the last pair is the first that does.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, ok := collect.Of("a", "b", "c").Keyed().After(func(_ int, s string) bool { return s == "a" })
fmt.Println(k, v, ok)
}
Output: 1 b true
func (KeyedCollection[K, V]) AvgBy ¶
func (c KeyedCollection[K, V]) AvgBy[N Number](f func(K, V) N) (float64, bool)
AvgBy returns the mean of the numbers f returns for the pairs. It is false for an empty collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
prices := collect.FromMap(map[string]int{"desk": 200, "chair": 100})
fmt.Println(prices.AvgBy(func(_ string, price int) int { return price }))
}
Output: 150 true
func (KeyedCollection[K, V]) Before ¶
func (c KeyedCollection[K, V]) Before(match func(K, V) bool) (K, V, bool)
Before returns the pair just before the first for which match returns true. It is false if no pair matches, or if the first pair does.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, ok := collect.Of("a", "b", "c").Keyed().Before(func(_ int, s string) bool { return s == "c" })
fmt.Println(k, v, ok)
}
Output: 1 b true
func (KeyedCollection[K, V]) Chunk ¶
func (c KeyedCollection[K, V]) Chunk[C interface{ KeyedCollection[K, V] }](size int) Collection[C]
Chunk returns the pairs in keyed collections of size pairs each, as Laravel's chunk does: each pair keeps its key. The last one has fewer if the pairs run out. It panics with ErrInvalidArgument if size is less than 1.
C is always KeyedCollection[K, V], and Go infers it, as with Collection.Chunk.
Example ¶
Each pair keeps its key, as in Laravel: the second chunk starts at key 2.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
chunks := collect.Of("a", "b", "c", "d", "e").Keyed().Chunk(2)
for chunk := range chunks.Seq() {
fmt.Println(chunk.Keys().All(), chunk.Values().All())
}
}
Output: [0 1] [a b] [2 3] [c d] [4] [e]
func (KeyedCollection[K, V]) ChunkBy ¶
func (c KeyedCollection[K, V]) ChunkBy[E comparable, C interface{ KeyedCollection[K, V] }](f func(K, V) E) Collection[C]
ChunkBy returns runs of adjacent pairs that have the same key, as f returns it. Each pair keeps its own key. C is always KeyedCollection[K, V], and Go infers it.
Example ¶
Each pair of a chunk keeps its key.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
chunks := collect.Of(1, 3, 2).Keyed().ChunkBy(func(_, n int) bool { return n%2 == 0 })
for chunk := range chunks.Seq() {
fmt.Println(chunk.Keys().All())
}
}
Output: [0 1] [2]
func (KeyedCollection[K, V]) ChunkWhile ¶
func (c KeyedCollection[K, V]) ChunkWhile[C interface{ KeyedCollection[K, V] }](keep func(k K, v V, chunk KeyedCollection[K, V]) bool) Collection[C]
ChunkWhile returns runs of pairs. A run goes on while keep returns true for the next pair and the run so far. Each pair keeps its own key. The run is valid only during the call. C is always KeyedCollection[K, V], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
same := func(_ int, letter string, chunk collect.KeyedCollection[int, string]) bool {
_, last, _ := chunk.Last()
return letter == last
}
chunks := collect.Of("A", "A", "B").Keyed().ChunkWhile(same)
for chunk := range chunks.Seq() {
fmt.Println(chunk.Keys().All(), chunk.Values().All())
}
}
Output: [0 1] [A A] [2] [B]
func (KeyedCollection[K, V]) Concat ¶
func (c KeyedCollection[K, V]) Concat(others ...KeyedCollection[K, V]) KeyedCollection[K, V]
Concat returns the pairs of the collection, then of each of others, with their keys. A key may then come more than once.
Example ¶
The pairs keep their keys, so a key may come twice.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("a").Keyed().Concat(collect.Of("b").Keyed())
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0 0] [a b]
func (KeyedCollection[K, V]) Contains ¶
func (c KeyedCollection[K, V]) Contains(match func(K, V) bool) bool
Contains reports whether match returns true for a pair. It reads no pair past that one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]string{"name": "Desk", "price": "100"})
fmt.Println(c.Contains(func(_, v string) bool { return v == "Desk" }))
}
Output: true
func (KeyedCollection[K, V]) Count ¶
func (c KeyedCollection[K, V]) Count() int
Count reads the collection and returns how many pairs it has. A key that comes more than once is counted each time.
Example ¶
A key that comes more than once is counted each time.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("apple", "avocado").KeyBy(func(s string) string { return s[:1] })
fmt.Println(c.Count(), len(c.ToMap()))
}
Output: 2 1
func (KeyedCollection[K, V]) CountBy ¶
func (c KeyedCollection[K, V]) CountBy[G comparable](f func(K, V) G) KeyedCollection[G, int]
CountBy counts the pairs by the key f returns for each. The counts are in the order their keys first come. It reads every pair before it yields the first count.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromSeq2(slices.All([]string{"apple", "avocado", "banana"}))
fmt.Println(c.CountBy(func(_ int, s string) string { return s[:1] }).ToMap())
}
Output: map[a:2 b:1]
func (KeyedCollection[K, V]) DiffAssocBy ¶
func (c KeyedCollection[K, V]) DiffAssocBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
DiffAssocBy returns the pairs that other does not have: other has no such key, or f returns something else for its value of the key. Pass Identity to compare the values. When other has a key twice, its last value counts. It reads other whole before the first pair.
Example ¶
Laravel's example of diffAssoc.
c := keyedOf([]string{"color", "type", "remain"}, []any{"orange", "fruit", 6})
got := c.DiffAssocBy(keyedOf([]string{"color", "type", "used"}, []any{"yellow", "fruit", 6}), collect.Identity)
fmt.Println(got.ToMap())
Output: map[color:orange remain:6]
func (KeyedCollection[K, V]) DiffBy ¶
func (c KeyedCollection[K, V]) DiffBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
DiffBy returns the pairs whose value has a key, as f returns it, that no value of other has. Each pair keeps its own key, as in Laravel. It reads other whole before the first pair.
Example ¶
DiffBy compares the values, and keeps the keys, as in Laravel.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 2, 3, 4, 5).Keyed().DiffBy(collect.Of(2, 4).Keyed(), collect.Identity)
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0 2 4] [1 3 5]
func (KeyedCollection[K, V]) DiffFunc ¶
func (c KeyedCollection[K, V]) DiffFunc(other KeyedCollection[K, V], eq func(a, b V) bool) KeyedCollection[K, V]
DiffFunc returns the pairs whose value equals no value of other, as eq tells. Each pair keeps its own key.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("A", "b").Keyed().DiffFunc(collect.Of("a").Keyed(), strings.EqualFold)
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [1] [b]
func (KeyedCollection[K, V]) DiffKeys ¶
func (c KeyedCollection[K, V]) DiffKeys(other KeyedCollection[K, V]) KeyedCollection[K, V]
DiffKeys returns the pairs whose key is not the key of a pair of other. It reads other whole before the first pair.
Example ¶
Laravel's example of diffKeys.
c := keyedOf([]string{"one", "two", "three", "four", "five"}, []int{10, 20, 30, 40, 50})
got := c.DiffKeys(keyedOf([]string{"two", "four", "six"}, []int{2, 4, 6}))
fmt.Println(got.Keys().All(), got.Values().All())
Output: [one three five] [10 30 50]
func (KeyedCollection[K, V]) DoesntContain ¶
func (c KeyedCollection[K, V]) DoesntContain(match func(K, V) bool) bool
DoesntContain reports whether match returns false for every pair.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]string{"name": "Desk"})
fmt.Println(c.DoesntContain(func(_, v string) bool { return v == "Table" }))
}
Output: true
func (KeyedCollection[K, V]) DuplicatesBy ¶
func (c KeyedCollection[K, V]) DuplicatesBy[E comparable](f func(K, V) E) KeyedCollection[K, E]
DuplicatesBy returns what f returns for each pair, each time it returns what it returned for a pair before, with that pair's own key, as Laravel's duplicates does.
Example ¶
Laravel's example of duplicates: each repeat, with its own key.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("a", "b", "a", "c", "b").Keyed().DuplicatesBy(func(_ int, s string) string { return s })
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [2 4] [a b]
func (KeyedCollection[K, V]) Each ¶
func (c KeyedCollection[K, V]) Each(f func(K, V))
Each calls f with each pair, in order. To stop early, range over KeyedCollection.Seq and break.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
collect.Of("a", "b").Keyed().Each(func(i int, s string) { fmt.Println(i, s) })
}
Output: 0 a 1 b
func (KeyedCollection[K, V]) Eager ¶
func (c KeyedCollection[K, V]) Eager() KeyedCollection[K, V]
Eager reads every pair now, and returns a collection of them, in order and with every key, even one that comes more than once.
Example ¶
c := once("a", "b").Keyed().Eager()
fmt.Println(c.Keys().All(), c.Keys().All())
Output: [0 1] [0 1]
func (KeyedCollection[K, V]) Ensure ¶
func (c KeyedCollection[K, V]) Ensure[U any]() (KeyedCollection[K, U], error)
Ensure reads every pair now, and returns them with their values as U. The error wraps ErrUnexpectedValue and names the first value that is not a U. Write U: c.Ensure[*Dog]().
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c, err := collect.FromMap(map[string]any{"a": 1}).Ensure[int]()
fmt.Println(c.ToMap(), err)
}
Output: map[a:1] <nil>
func (KeyedCollection[K, V]) Entries ¶
func (c KeyedCollection[K, V]) Entries[E interface{ Entry[K, V] }]() Collection[E]
Entries returns each pair as an Entry, in order and with every repeated key, as ECMAScript's Map.prototype.entries does. Entries().All() is the pairs in order, which KeyedCollection.ToMap cannot keep. E is always Entry[K, V], and Go infers it, as with Collection.Chunk.
Example ¶
Entries keeps the order and every repeated key, which ToMap does not.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("apple", "avocado", "banana").KeyBy(func(s string) string { return s[:1] })
fmt.Println(c.Entries().All())
fmt.Println(c.ToMap())
}
Output: [{a apple} {a avocado} {b banana}] map[a:avocado b:banana]
func (KeyedCollection[K, V]) Every ¶
func (c KeyedCollection[K, V]) Every(match func(K, V) bool) bool
Every reports whether match returns true for every pair. It is true for an empty collection. It reads no pair past the first that fails.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 2).Keyed()
fmt.Println(c.Every(func(i, n int) bool { return n == i+1 }))
}
Output: true
func (KeyedCollection[K, V]) Except ¶
func (c KeyedCollection[K, V]) Except(keys ...K) KeyedCollection[K, V]
Except returns the pairs whose key is none of keys.
Example ¶
Laravel's example of except.
c := keyedOf([]string{"product_id", "price", "discount"}, []any{1, 100, false})
fmt.Println(c.Except("price", "discount").ToMap())
Output: map[product_id:1]
func (KeyedCollection[K, V]) Filter ¶
func (c KeyedCollection[K, V]) Filter(keep func(K, V) bool) KeyedCollection[K, V]
Filter returns the pairs for which keep returns true, with their keys.
Example ¶
Filter keeps the keys, and Values drops them: Laravel's filter and values, made explicit.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
odd := collect.Of(10, 11, 12, 13).Keyed().
Filter(func(_, n int) bool { return n%2 == 1 })
fmt.Println(odd.Keys().All(), odd.Values().All())
}
Output: [1 3] [11 13]
func (KeyedCollection[K, V]) First ¶
func (c KeyedCollection[K, V]) First() (K, V, bool)
First returns the first pair. It is false if there is none. It reads at most one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, ok := collect.Of("a", "b").Keyed().First()
fmt.Println(k, v, ok)
}
Output: 0 a true
func (KeyedCollection[K, V]) FirstWhere ¶
func (c KeyedCollection[K, V]) FirstWhere(match func(K, V) bool) (K, V, bool)
FirstWhere returns the first pair for which match returns true. It is false if there is none. It reads no pair past that one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, ok := collect.Of("a", "b", "c").Keyed().
FirstWhere(func(_ int, s string) bool { return s > "a" })
fmt.Println(k, v, ok)
}
Output: 1 b true
func (KeyedCollection[K, V]) FlatMap ¶
func (c KeyedCollection[K, V]) FlatMap[K2 comparable, U any](f func(K, V) KeyedCollection[K2, U]) KeyedCollection[K2, U]
FlatMap returns the pairs of the keyed collections f returns, in order, as one keyed collection.
Example ¶
package main
import (
"fmt"
"slices"
"strings"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromSeq2(slices.All([]string{"a b", "c"})).
FlatMap(func(_ int, s string) collect.KeyedCollection[int, string] {
return collect.FromSeq2(slices.All(strings.Fields(s)))
})
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0 1 0] [a b c]
func (KeyedCollection[K, V]) FlipBy ¶
func (c KeyedCollection[K, V]) FlipBy[K2 comparable](f func(V) K2) KeyedCollection[K2, K]
FlipBy returns the pairs with the key f returns for each value as the key, and the old key as the value. Pass Identity when the values are comparable.
Example ¶
Laravel's example of flip.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]string{"name": "taylor", "framework": "laravel"})
fmt.Println(c.FlipBy(collect.Identity).ToMap())
}
Output: map[laravel:framework taylor:name]
func (KeyedCollection[K, V]) ForPage ¶
func (c KeyedCollection[K, V]) ForPage(page, perPage int) KeyedCollection[K, V]
ForPage returns the pairs of page page, from 1, with perPage pairs to a page, with their keys, as Collection.ForPage does.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(1, 9).Keyed().ForPage(2, 3).Keys().All())
}
Output: [3 4 5]
func (KeyedCollection[K, V]) Get ¶
func (c KeyedCollection[K, V]) Get(k K) (V, bool)
Get returns the value of the first pair with key k. It is false if there is none. It reads no pair past that one. Note that KeyedCollection.ToMap keeps the last value of a key instead.
Example ¶
Laravel's example of get.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]string{"name": "taylor", "framework": "laravel"})
fmt.Println(c.Get("name"))
fmt.Println(c.Get("age"))
}
Output: taylor true false
func (KeyedCollection[K, V]) GroupBy ¶
func (c KeyedCollection[K, V]) GroupBy[G comparable, C interface{ KeyedCollection[K, V] }](f func(K, V) G) KeyedCollection[G, C]
GroupBy groups the pairs by the key f returns for each. Each group keeps the pairs' own keys, as Laravel's groupBy with preserveKeys does. It reads every pair before it yields the first group. C is always KeyedCollection[K, V], and Go infers it.
Example ¶
The groups of a KeyedCollection keep their pairs' keys.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
groups := collect.Of(10, 11, 12, 13).Keyed().
GroupBy(func(_, n int) string { return map[bool]string{true: "even", false: "odd"}[n%2 == 0] })
for parity, group := range groups.Seq() {
fmt.Println(parity, group.Keys().All(), group.Values().All())
}
}
Output: even [0 2] [10 12] odd [1 3] [11 13]
func (KeyedCollection[K, V]) Has ¶
func (c KeyedCollection[K, V]) Has(keys ...K) bool
Has reports whether every one of keys is the key of a pair. It reads no pair past the one that completes them. It is true for no keys.
Example ¶
Laravel's examples of has.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"account_id": 1, "product": 2, "amount": 5})
fmt.Println(c.Has("product"))
fmt.Println(c.Has("product", "amount"))
fmt.Println(c.Has("amount", "price"))
}
Output: true true false
func (KeyedCollection[K, V]) HasAny ¶
func (c KeyedCollection[K, V]) HasAny(keys ...K) bool
HasAny reports whether any of keys is the key of a pair. It reads no pair past the first that has one.
Example ¶
Laravel's examples of hasAny.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"account_id": 1, "product": 2, "amount": 5})
fmt.Println(c.HasAny("product", "price"))
fmt.Println(c.HasAny("name", "price"))
}
Output: true false
func (KeyedCollection[K, V]) HasMany ¶
func (c KeyedCollection[K, V]) HasMany() bool
HasMany reports whether the collection has more than one pair. It reads at most two, and drops them, as Collection.IsEmpty does. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.FromMap(map[string]int{"a": 1, "b": 2}).HasMany())
}
Output: true
func (KeyedCollection[K, V]) HasSole ¶
func (c KeyedCollection[K, V]) HasSole() bool
HasSole reports whether the collection has exactly one pair. It reads at most two, and drops them, as Collection.IsEmpty does. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.FromMap(map[string]int{"a": 1}).HasSole())
}
Output: true
func (KeyedCollection[K, V]) ImplodeBy ¶
func (c KeyedCollection[K, V]) ImplodeBy[S ~string](f func(K, V) S, sep string) string
ImplodeBy joins the strings f returns for the pairs, with sep between them.
Example ¶
c := keyedOf([]string{"a", "b"}, []int{1, 2})
fmt.Println(c.ImplodeBy(func(k string, v int) string { return fmt.Sprintf("%s=%d", k, v) }, "&"))
Output: a=1&b=2
func (KeyedCollection[K, V]) IntersectAssocBy ¶
func (c KeyedCollection[K, V]) IntersectAssocBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
IntersectAssocBy returns the pairs that other has too: the same key, and a value for which f returns the same. Pass Identity to compare the values. When other has a key twice, its last value counts. It reads other whole before the first pair.
Example ¶
Laravel's example of intersectAssoc.
c := keyedOf([]string{"color", "size", "material"}, []string{"red", "M", "cotton"})
got := c.IntersectAssocBy(keyedOf([]string{"color", "size", "material"}, []string{"blue", "M", "polyester"}), collect.Identity)
fmt.Println(got.ToMap())
Output: map[size:M]
func (KeyedCollection[K, V]) IntersectBy ¶
func (c KeyedCollection[K, V]) IntersectBy[E comparable](other KeyedCollection[K, V], f func(V) E) KeyedCollection[K, V]
IntersectBy returns the pairs whose value has a key, as f returns it, that a value of other has. Each pair keeps its own key. It reads other whole before the first pair.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("Desk", "Sofa", "Chair").Keyed().IntersectBy(collect.Of("Desk", "Chair").Keyed(), collect.Identity)
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0 2] [Desk Chair]
func (KeyedCollection[K, V]) IntersectFunc ¶
func (c KeyedCollection[K, V]) IntersectFunc(other KeyedCollection[K, V], eq func(a, b V) bool) KeyedCollection[K, V]
IntersectFunc returns the pairs whose value equals a value of other, as eq tells. Each pair keeps its own key.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("A", "b").Keyed().IntersectFunc(collect.Of("a").Keyed(), strings.EqualFold)
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0] [A]
func (KeyedCollection[K, V]) IntersectKeys ¶
func (c KeyedCollection[K, V]) IntersectKeys(other KeyedCollection[K, V]) KeyedCollection[K, V]
IntersectKeys returns the pairs whose key is the key of a pair of other. It is Laravel's intersectByKeys, named as KeyedCollection.DiffKeys is. It reads other whole before the first pair.
Example ¶
Laravel's example of intersectByKeys.
c := keyedOf([]string{"serial", "type", "year"}, []any{"UX301", "screen", 2009})
got := c.IntersectKeys(keyedOf([]string{"reference", "type", "year"}, []any{"UX404", "tab", 2011}))
fmt.Println(got.ToMap())
Output: map[type:screen year:2009]
func (KeyedCollection[K, V]) IsEmpty ¶
func (c KeyedCollection[K, V]) IsEmpty() bool
IsEmpty reports whether the collection has no pairs. It reads at most one, as Collection.IsEmpty does, and drops it. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.FromMap(map[string]int{}).IsEmpty())
}
Output: true
func (KeyedCollection[K, V]) IsNotEmpty ¶
func (c KeyedCollection[K, V]) IsNotEmpty() bool
IsNotEmpty reports whether the collection has a pair. It reads at most one, and drops it, as Collection.IsEmpty does. A source that can be read once loses what it reads: call Remember first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.FromMap(map[string]int{"a": 1}).IsNotEmpty())
}
Output: true
func (KeyedCollection[K, V]) JoinBy ¶
func (c KeyedCollection[K, V]) JoinBy[S ~string](f func(K, V) S, sep string) string
JoinBy is KeyedCollection.ImplodeBy, under the name of strings.Join.
Example ¶
c := keyedOf([]string{"a", "b"}, []int{1, 2})
fmt.Println(c.JoinBy(func(k string, _ int) string { return k }, "/"))
Output: a/b
func (KeyedCollection[K, V]) JoinFinalBy ¶
func (c KeyedCollection[K, V]) JoinFinalBy[S ~string](f func(K, V) S, glue, finalGlue string) string
JoinFinalBy joins the strings f returns for the pairs, with glue between them and finalGlue before the last, as Collection.JoinFinalBy does.
Example ¶
c := keyedOf([]string{"a", "b", "c"}, []int{1, 2, 3})
fmt.Println(c.JoinFinalBy(func(k string, _ int) string { return k }, ", ", " and "))
Output: a, b and c
func (KeyedCollection[K, V]) KeyBy ¶
func (c KeyedCollection[K, V]) KeyBy[K2 comparable](f func(K, V) K2) KeyedCollection[K2, V]
KeyBy returns the values with the key f returns for each pair as their new key.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]string{"a": "apple"}).
KeyBy(func(k, v string) string { return strings.ToUpper(k) })
fmt.Println(c.ToMap())
}
Output: map[A:apple]
func (KeyedCollection[K, V]) Keys ¶
func (c KeyedCollection[K, V]) Keys() Collection[K]
Keys returns the keys without their values. A key that comes more than once is there each time.
Example ¶
A key that comes more than once is there each time.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
keys := collect.Of("apple", "avocado", "banana").
KeyBy(func(s string) string { return s[:1] }).
Keys().
All()
fmt.Println(keys)
}
Output: [a a b]
func (KeyedCollection[K, V]) Last ¶
func (c KeyedCollection[K, V]) Last() (K, V, bool)
Last returns the last pair. It is false if there is none. It reads every pair.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, ok := collect.Of("a", "b").Keyed().Last()
fmt.Println(k, v, ok)
}
Output: 1 b true
func (KeyedCollection[K, V]) Map ¶
func (c KeyedCollection[K, V]) Map[U any](f func(K, V) U) KeyedCollection[K, U]
Map returns the keys with f applied to each pair as their values.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("a", "b").Keyed().
Map(func(i int, s string) string { return strings.Repeat(s, i+1) })
for k, v := range c.Seq() {
fmt.Println(k, v)
}
}
Output: 0 a 1 bb
func (KeyedCollection[K, V]) MapToGroups ¶
func (c KeyedCollection[K, V]) MapToGroups[G comparable, U any](f func(K, V) (G, U)) KeyedCollection[G, Collection[U]]
MapToGroups groups the values f returns by the keys it returns with them, as Collection.MapToGroups does.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/mpyw/collect"
)
func main() {
groups := collect.FromSeq2(slices.All([]string{"apple", "avocado", "banana"})).
MapToGroups(func(i int, s string) (string, int) { return s[:1], i })
for initial, indexes := range groups.Seq() {
fmt.Println(initial, indexes.All())
}
}
Output: a [0 1] b [2]
func (KeyedCollection[K, V]) MapWithKeys ¶
func (c KeyedCollection[K, V]) MapWithKeys[K2 comparable, U any](f func(K, V) (K2, U)) KeyedCollection[K2, U]
MapWithKeys returns the key and value f returns for each pair.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
ages := collect.FromMap(map[string]int{"Alice": 31})
byAge := ages.MapWithKeys(func(name string, age int) (int, string) { return age, name })
fmt.Println(byAge.ToMap())
}
Output: map[31:Alice]
func (KeyedCollection[K, V]) MarshalJSONTo ¶
func (c KeyedCollection[K, V]) MarshalJSONTo(enc *jsontext.Encoder) error
MarshalJSONTo writes the pairs to enc as a JSON object, in order, as each is read. It is an object even when the keys are 0, 1, 2 and so on, where PHP would write an array.
A key that encodes as a JSON string, with enc's options, is the name. A number or a boolean is quoted, as json.Marshal quotes the keys of a map. Any other key is an error that wraps ErrUnsupportedKey. A key that comes twice is an error in encoding/json/v2, unless enc allows it with jsontext.AllowDuplicateNames. encoding/json allows it.
Example ¶
package main
import (
jsonv2 "encoding/json/v2"
"fmt"
"github.com/mpyw/collect"
)
func main() {
b, err := jsonv2.Marshal(collect.Of("x", "y").Keyed())
fmt.Println(string(b), err)
}
Output: {"0":"x","1":"y"} <nil>
func (KeyedCollection[K, V]) MaxBy ¶
func (c KeyedCollection[K, V]) MaxBy[O cmp.Ordered](f func(K, V) O) (O, bool)
MaxBy returns the greatest of the keys f returns for the pairs. It is false for an empty collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
prices := collect.FromMap(map[string]int{"desk": 200, "chair": 100})
fmt.Println(prices.MaxBy(func(name string, _ int) string { return name }))
}
Output: desk true
func (KeyedCollection[K, V]) MedianBy ¶
func (c KeyedCollection[K, V]) MedianBy[N Number](f func(K, V) N) (float64, bool)
MedianBy returns the middle of the numbers f returns for the pairs, or the mean of the two middle ones. It is false for an empty collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(10, 30, 20).Keyed()
fmt.Println(c.MedianBy(func(_, n int) int { return n }))
}
Output: 20 true
func (KeyedCollection[K, V]) MinBy ¶
func (c KeyedCollection[K, V]) MinBy[O cmp.Ordered](f func(K, V) O) (O, bool)
MinBy returns the least of the keys f returns for the pairs. It is false for an empty collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
prices := collect.FromMap(map[string]int{"desk": 200, "chair": 100})
fmt.Println(prices.MinBy(func(_ string, price int) int { return price }))
}
Output: 100 true
func (KeyedCollection[K, V]) ModeBy ¶
func (c KeyedCollection[K, V]) ModeBy[E comparable](f func(K, V) E) Collection[E]
ModeBy returns the keys that f returns most often for the pairs, in the order they first come. It is empty for an empty collection. It reads every pair before it yields the first key.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 1, 2).Keyed()
fmt.Println(c.ModeBy(func(_, n int) int { return n }).All())
}
Output: [1]
func (KeyedCollection[K, V]) Multiply ¶
func (c KeyedCollection[K, V]) Multiply(n int) KeyedCollection[K, V]
Multiply returns the pairs n times over, with their keys. Each read reads the collection once, and repeats what it read. A negative n is 0.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b").Keyed().Multiply(2).Keys().All())
}
Output: [0 1 0 1]
func (KeyedCollection[K, V]) MustEnsure ¶
func (c KeyedCollection[K, V]) MustEnsure[U any]() KeyedCollection[K, U]
MustEnsure returns the pairs with their values as U, lazily. Reading a value that is not a U panics with the error KeyedCollection.Ensure would return.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.FromMap(map[string]any{"a": 1}).MustEnsure[int]().ToMap())
}
Output: map[a:1]
func (KeyedCollection[K, V]) MustFirst ¶
func (c KeyedCollection[K, V]) MustFirst() (K, V)
MustFirst returns the first pair. It panics with ErrItemNotFound if there is none. It reads at most one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b").Keyed().MustFirst())
}
Output: 0 a
func (KeyedCollection[K, V]) MustGet ¶
func (c KeyedCollection[K, V]) MustGet(k K) V
MustGet returns the value of the first pair with key k. It panics with an error that wraps ErrItemNotFound and names k if there is none. KeyedCollection.Get reports the absence instead.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]string{"name": "taylor"})
fmt.Println(c.MustGet("name"))
defer func() { fmt.Println("panic:", recover()) }()
c.MustGet("age")
}
Output: taylor panic: collect: item not found: no key age
func (KeyedCollection[K, V]) MustLast ¶
func (c KeyedCollection[K, V]) MustLast() (K, V)
MustLast returns the last pair. It panics with ErrItemNotFound if there is none. It reads every pair.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b").Keyed().MustLast())
}
Output: 1 b
func (KeyedCollection[K, V]) MustSole ¶
func (c KeyedCollection[K, V]) MustSole() (K, V)
MustSole returns the only pair. It panics with the error KeyedCollection.Sole would return. It reads at most two.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.FromMap(map[string]int{"only": 1}).MustSole())
}
Output: only 1
func (KeyedCollection[K, V]) Nth ¶
func (c KeyedCollection[K, V]) Nth(step, offset int) KeyedCollection[K, V]
Nth returns every step-th pair, starting at offset, with their keys. A negative offset counts from the end. It panics with ErrInvalidArgument if step is less than 1.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c", "d", "e", "f").Keyed().Nth(4, 1).Keys().All())
}
Output: [1 5]
func (KeyedCollection[K, V]) Only ¶
func (c KeyedCollection[K, V]) Only(keys ...K) KeyedCollection[K, V]
Only returns the first pair of each of keys, in the collection's order. It reads no pair past the one that completes them, as Laravel's lazy only does.
Example ¶
Laravel's example of only.
c := keyedOf([]string{"product_id", "name", "price", "discount"}, []any{1, "Desk", 100, false})
fmt.Println(c.Only("product_id", "name").ToMap())
Output: map[name:Desk product_id:1]
func (KeyedCollection[K, V]) Partition ¶
func (c KeyedCollection[K, V]) Partition(match func(K, V) bool) (KeyedCollection[K, V], KeyedCollection[K, V])
Partition returns the pairs for which match returns true, and those for which it returns false, with their keys. It reads the collection once, when either result is first read, and keeps both, as Collection.Partition does.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
even, odd := collect.Of("a", "b", "c").Keyed().Partition(func(i int, _ string) bool { return i%2 == 0 })
fmt.Println(even.Keys().All(), odd.Keys().All())
}
Output: [0 2] [1]
func (KeyedCollection[K, V]) Percentage ¶
func (c KeyedCollection[K, V]) Percentage(match func(K, V) bool, precision int) (float64, bool)
Percentage returns the percentage of the pairs for which match returns true, rounded to precision decimal places. It is false for an empty collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 1, 2, 2, 2, 3).Keyed()
fmt.Println(c.Percentage(func(_, n int) bool { return n == 1 }, 2))
}
Output: 33.33 true
func (KeyedCollection[K, V]) Pipe ¶
func (c KeyedCollection[K, V]) Pipe[U any](f func(KeyedCollection[K, V]) U) U
Pipe returns what f returns for the collection.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a").Keyed().Pipe(collect.KeyedCollection[int, string].Count))
}
Output: 1
func (KeyedCollection[K, V]) PipeThrough ¶
func (c KeyedCollection[K, V]) PipeThrough(fs ...func(KeyedCollection[K, V]) KeyedCollection[K, V]) KeyedCollection[K, V]
PipeThrough passes the collection through each of fs in turn, and returns what the last returns.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
first := func(c collect.KeyedCollection[int, string]) collect.KeyedCollection[int, string] { return c.Take(1) }
fmt.Println(collect.Of("a", "b").Keyed().PipeThrough(first).Values().All())
}
Output: [a]
func (KeyedCollection[K, V]) Random ¶
func (c KeyedCollection[K, V]) Random() (K, V, bool)
Random returns a pair chosen at random. It is false for an empty collection. It reads every pair, and keeps only one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, ok := collect.Of("a", "b").Keyed().Random()
fmt.Println((k == 0 && v == "a") || (k == 1 && v == "b"), ok)
}
Output: true true
func (KeyedCollection[K, V]) RandomN ¶
func (c KeyedCollection[K, V]) RandomN(n int) (KeyedCollection[K, V], error)
RandomN reads every pair now, and returns n of them chosen at random, in the order they come, with their keys. The error wraps ErrNotEnoughItems if there are fewer than n. A negative n is 0, as in Laravel.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c, err := collect.Range(1, 5).Keyed().RandomN(3)
fmt.Println(c.Count(), err)
}
Output: 3 <nil>
func (KeyedCollection[K, V]) Reduce ¶
func (c KeyedCollection[K, V]) Reduce[A any](f func(A, K, V) A, initial A) A
Reduce returns f applied to the result so far and each pair in turn, starting from initial. It is Laravel's reduceWithKeys.
Example ¶
Laravel's example of reduceWithKeys.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
prices := collect.MustCombine(collect.Of("usd", "gbp", "eur"), collect.Of(1400, 1200, 1000))
rates := map[string]int{"usd": 1, "gbp": 1, "eur": 1}
total := prices.Reduce(func(carry int, currency string, n int) int { return carry + n*rates[currency] }, 0)
fmt.Println(total)
}
Output: 3600
func (KeyedCollection[K, V]) Reject ¶
func (c KeyedCollection[K, V]) Reject(drop func(K, V) bool) KeyedCollection[K, V]
Reject returns the pairs for which drop returns false, with their keys.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("a", "b", "c").Keyed().
Reject(func(i int, _ string) bool { return i == 0 })
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [1 2] [b c]
func (KeyedCollection[K, V]) Remember ¶
func (c KeyedCollection[K, V]) Remember() KeyedCollection[K, V]
Remember returns a collection that reads the source once, and keeps each pair it reads, as Collection.Remember does.
Example ¶
c := once("a", "b").Keyed().Remember()
fmt.Println(c.Keys().All(), c.Keys().All())
Output: [0 1] [0 1]
func (KeyedCollection[K, V]) Replace ¶
func (c KeyedCollection[K, V]) Replace(other KeyedCollection[K, V]) KeyedCollection[K, V]
Replace returns the pairs, with the value of other for each key that other has, then the pairs of other whose key the collection does not have. It reads other whole before the first pair. It is also Laravel's merge of keyed collections: a Go key is never renumbered.
Example ¶
Laravel's example of replace.
c := collect.Of("Taylor", "Abigail", "James").Keyed().
Replace(keyedOf([]int{1, 3}, []string{"Victoria", "Finn"}))
fmt.Println(c.Values().All())
Output: [Taylor Victoria James Finn]
func (KeyedCollection[K, V]) Reverse ¶
func (c KeyedCollection[K, V]) Reverse() KeyedCollection[K, V]
Reverse returns the pairs last first, with their keys. It reads every pair before the first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b").Keyed().Reverse().Keys().All())
}
Output: [1 0]
func (KeyedCollection[K, V]) Search ¶
func (c KeyedCollection[K, V]) Search(match func(K, V) bool) (K, bool)
Search returns the key of the first pair for which match returns true. It is false if there is none.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("Taylor", "Abigail").KeyBy(func(s string) string { return strings.ToLower(s[:1]) })
k, ok := c.Search(func(_, name string) bool { return name == "Abigail" })
fmt.Println(k, ok)
}
Output: a true
func (KeyedCollection[K, V]) Seq ¶
func (c KeyedCollection[K, V]) Seq() iter.Seq2[K, V]
Seq returns the sequence of the keys and values, for a range loop or for the iter, slices and maps packages.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for k, v := range collect.Of("a", "b").Keyed().Seq() {
fmt.Println(k, v)
}
}
Output: 0 a 1 b
func (KeyedCollection[K, V]) Shuffle ¶
func (c KeyedCollection[K, V]) Shuffle() KeyedCollection[K, V]
Shuffle returns the pairs in a random order, new on each read, with their keys. It reads every pair before the first.
Example ¶
Each pair keeps its key.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(10, 20, 30).Keyed().Shuffle()
fmt.Println(c.Every(func(i, n int) bool { return n == (i+1)*10 }), c.Count())
}
Output: true 3
func (KeyedCollection[K, V]) Skip ¶
func (c KeyedCollection[K, V]) Skip(n int) KeyedCollection[K, V]
Skip returns the pairs after the first n. A negative n is 0.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c").Keyed().Skip(2).Keys().All())
}
Output: [2]
func (KeyedCollection[K, V]) SkipUntil ¶
func (c KeyedCollection[K, V]) SkipUntil(match func(K, V) bool) KeyedCollection[K, V]
SkipUntil returns the pairs from the first for which match returns true.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 2, 3, 1).Keyed().SkipUntil(func(_, n int) bool { return n == 3 })
fmt.Println(c.Keys().All())
}
Output: [2 3]
func (KeyedCollection[K, V]) SkipWhile ¶
func (c KeyedCollection[K, V]) SkipWhile(match func(K, V) bool) KeyedCollection[K, V]
SkipWhile returns the pairs from the first for which match returns false.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 2, 3, 1).Keyed().SkipWhile(func(_, n int) bool { return n < 3 })
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [2 3] [3 1]
func (KeyedCollection[K, V]) Slice ¶
func (c KeyedCollection[K, V]) Slice(offset, length int) KeyedCollection[K, V]
Slice returns length pairs from offset, as PHP's array_slice does, with their keys. Negative values count from the end, as in Collection.Slice.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Range(1, 10).Keyed().Slice(-2, 1).Keys().All())
}
Output: [8]
func (KeyedCollection[K, V]) Sliding ¶
func (c KeyedCollection[K, V]) Sliding[C interface{ KeyedCollection[K, V] }](size, step int) Collection[C]
Sliding returns windows of size pairs, each step pairs after the one before, as Collection.Sliding does. Each pair keeps its own key. C is always KeyedCollection[K, V], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for window := range collect.Of("a", "b", "c").Keyed().Sliding(2, 1).Seq() {
fmt.Println(window.Keys().All())
}
}
Output: [0 1] [1 2]
func (KeyedCollection[K, V]) Sole ¶
func (c KeyedCollection[K, V]) Sole() (K, V, error)
Sole returns the only pair. The error is ErrItemNotFound if there is none, and ErrMultipleItemsFound if there is more than one. It reads at most two.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
k, v, err := collect.FromMap(map[string]int{"only": 1}).Sole()
fmt.Println(k, v, err)
}
Output: only 1 <nil>
func (KeyedCollection[K, V]) SortBy ¶
func (c KeyedCollection[K, V]) SortBy[O cmp.Ordered](f func(K, V) O) KeyedCollection[K, V]
SortBy returns the pairs sorted by the key f returns for each, least first, with their own keys. It reads every pair before the first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(3, 1, 2).Keyed().SortBy(func(_, n int) int { return n })
fmt.Println(c.Keys().All())
}
Output: [1 2 0]
func (KeyedCollection[K, V]) SortByDesc ¶
func (c KeyedCollection[K, V]) SortByDesc[O cmp.Ordered](f func(K, V) O) KeyedCollection[K, V]
SortByDesc returns the pairs sorted by the key f returns for each, greatest first, with their own keys. It reads every pair before the first.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(3, 1, 2).Keyed().SortByDesc(func(_, n int) int { return n })
fmt.Println(c.Keys().All())
}
Output: [0 2 1]
func (KeyedCollection[K, V]) SortFunc ¶
func (c KeyedCollection[K, V]) SortFunc(cmp func(ak K, av V, bk K, bv V) int) KeyedCollection[K, V]
SortFunc returns the pairs sorted by cmp, with their keys, as Collection.SortFunc sorts values.
Example ¶
package main
import (
"cmp"
"fmt"
"github.com/mpyw/collect"
)
func main() {
byValue := func(_ int, a string, _ int, b string) int { return cmp.Compare(a, b) }
c := collect.Of("b", "a").Keyed().SortFunc(byValue)
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [1 0] [a b]
func (KeyedCollection[K, V]) SortKeysBy ¶
func (c KeyedCollection[K, V]) SortKeysBy[O cmp.Ordered](f func(K) O) KeyedCollection[K, V]
SortKeysBy returns the pairs sorted by what f returns for each key, least first. Pass Identity for ordered keys.
Example ¶
Laravel's example of sortKeys.
c := keyedOf([]string{"id", "first", "last"}, []any{22345, "John", "Doe"}).SortKeysBy(collect.Identity)
fmt.Println(c.Keys().All())
Output: [first id last]
func (KeyedCollection[K, V]) SortKeysByDesc ¶
func (c KeyedCollection[K, V]) SortKeysByDesc[O cmp.Ordered](f func(K) O) KeyedCollection[K, V]
SortKeysByDesc returns the pairs sorted by what f returns for each key, greatest first. Pass Identity for ordered keys.
Example ¶
Laravel's sortKeysDesc.
c := keyedOf([]string{"id", "first", "last"}, []any{22345, "John", "Doe"}).SortKeysByDesc(collect.Identity)
fmt.Println(c.Keys().All())
Output: [last id first]
func (KeyedCollection[K, V]) SortKeysFunc ¶
func (c KeyedCollection[K, V]) SortKeysFunc(cmp func(a, b K) int) KeyedCollection[K, V]
SortKeysFunc returns the pairs sorted by cmp of their keys. It is Laravel's sortKeysUsing.
Example ¶
Laravel's example of sortKeysUsing, with the order of strnatcasecmp's letters.
fold := func(a, b string) int { return strings.Compare(strings.ToLower(a), strings.ToLower(b)) }
c := keyedOf([]string{"ID", "first", "last"}, []any{22345, "John", "Doe"}).SortKeysFunc(fold)
fmt.Println(c.Keys().All())
Output: [first ID last]
func (KeyedCollection[K, V]) Split ¶
func (c KeyedCollection[K, V]) Split[C interface{ KeyedCollection[K, V] }](n int) Collection[C]
Split returns the pairs in n groups, as even in size as can be, as Collection.Split does. Each pair keeps its own key. C is always KeyedCollection[K, V], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for group := range collect.Range(1, 5).Keyed().Split(3).Seq() {
fmt.Println(group.Keys().All())
}
}
Output: [0 1] [2 3] [4]
func (KeyedCollection[K, V]) SplitIn ¶
func (c KeyedCollection[K, V]) SplitIn[C interface{ KeyedCollection[K, V] }](n int) Collection[C]
SplitIn returns the pairs in n groups, each full but the last, as Collection.SplitIn does. Each pair keeps its own key. C is always KeyedCollection[K, V], and Go infers it.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
for group := range collect.Range(1, 5).Keyed().SplitIn(2).Seq() {
fmt.Println(group.Keys().All())
}
}
Output: [0 1 2] [3 4]
func (KeyedCollection[K, V]) SumBy ¶
func (c KeyedCollection[K, V]) SumBy[N Number](f func(K, V) N) N
SumBy returns the sum of the numbers f returns for the pairs.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
prices := collect.FromMap(map[string]int{"desk": 200, "chair": 100})
fmt.Println(prices.SumBy(func(_ string, price int) int { return price }))
}
Output: 300
func (KeyedCollection[K, V]) Take ¶
func (c KeyedCollection[K, V]) Take(n int) KeyedCollection[K, V]
Take returns the first n pairs, or all of them if there are fewer. It reads no pair past the nth. A negative n takes the last -n pairs, and reads every pair.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of("a", "b", "c").Keyed()
fmt.Println(c.Take(2).Keys().All(), c.Take(-1).Keys().All())
}
Output: [0 1] [2]
func (KeyedCollection[K, V]) TakeUntil ¶
func (c KeyedCollection[K, V]) TakeUntil(match func(K, V) bool) KeyedCollection[K, V]
TakeUntil returns the pairs before the first for which match returns true. It reads no pair past that one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c").Keyed().TakeUntil(func(i int, _ string) bool { return i == 2 }).Values().All())
}
Output: [a b]
func (KeyedCollection[K, V]) TakeWhile ¶
func (c KeyedCollection[K, V]) TakeWhile(match func(K, V) bool) KeyedCollection[K, V]
TakeWhile returns the pairs up to the first for which match returns false. It reads no pair past that one.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
fmt.Println(collect.Of("a", "b", "c").Keyed().TakeWhile(func(i int, _ string) bool { return i < 1 }).Values().All())
}
Output: [a]
func (KeyedCollection[K, V]) TapEach ¶
func (c KeyedCollection[K, V]) TapEach(f func(K, V)) KeyedCollection[K, V]
TapEach returns the same pairs, calling f with each as it is read.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
collect.Of("a").Keyed().TapEach(func(i int, s string) { fmt.Println(i, s) }).ToMap()
}
Output: 0 a
func (KeyedCollection[K, V]) ToMap ¶
func (c KeyedCollection[K, V]) ToMap() map[K]V
ToMap reads every pair into a new map. A map has no order, and keeps one value of each key: when a key comes more than once, its last value wins. Entries().All() keeps the order and every pair. It stands for Laravel's all, which keeps the order of a PHP array.
Example ¶
A key that comes more than once keeps its last value.
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
byInitial := collect.Of("apple", "avocado", "banana").
KeyBy(func(s string) string { return s[:1] }).
ToMap()
fmt.Println(byInitial)
}
Output: map[a:avocado b:banana]
func (KeyedCollection[K, V]) Union ¶
func (c KeyedCollection[K, V]) Union(other KeyedCollection[K, V]) KeyedCollection[K, V]
Union returns the pairs, then the pairs of other whose key is not the key of a pair before, as PHP's + on arrays does. When other has a key twice, its last value counts, as Laravel reads other into an array. It reads other whole before the first pair.
Example ¶
Laravel's example of union.
c := keyedOf([]int{1, 2}, []string{"a", "b"}).
Union(keyedOf([]int{3, 1}, []string{"c", "b"}))
fmt.Println(c.ToMap())
Output: map[1:a 2:b 3:c]
func (KeyedCollection[K, V]) UniqueBy ¶
func (c KeyedCollection[K, V]) UniqueBy[E comparable](f func(K, V) E) KeyedCollection[K, V]
UniqueBy returns the first pair of each key, as f returns it, with its own key.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of(1, 1, 2).Keyed().UniqueBy(func(_, n int) int { return n })
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0 2] [1 2]
func (KeyedCollection[K, V]) Unless ¶
func (c KeyedCollection[K, V]) Unless(cond bool, f func(KeyedCollection[K, V]) KeyedCollection[K, V]) KeyedCollection[K, V]
Unless returns f applied to the collection if cond is false, and the collection itself if not.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
first := func(c collect.KeyedCollection[int, string]) collect.KeyedCollection[int, string] { return c.Take(1) }
fmt.Println(collect.Of("a", "b").Keyed().Unless(false, first).Values().All())
}
Output: [a]
func (KeyedCollection[K, V]) Values ¶
func (c KeyedCollection[K, V]) Values() Collection[V]
Values returns the values without their keys, as maps.Values does.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromSeq2(slices.All([]string{"a", "b"})).
Filter(func(i int, _ string) bool { return i > 0 })
fmt.Println(c.Values().All())
}
Output: [b]
func (KeyedCollection[K, V]) When ¶
func (c KeyedCollection[K, V]) When(cond bool, f func(KeyedCollection[K, V]) KeyedCollection[K, V]) KeyedCollection[K, V]
When returns f applied to the collection if cond is true, and the collection itself if not.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
first := func(c collect.KeyedCollection[int, string]) collect.KeyedCollection[int, string] { return c.Take(1) }
fmt.Println(collect.Of("a", "b").Keyed().When(true, first).Values().All())
fmt.Println(collect.Of("a", "b").Keyed().When(false, first).Values().All())
}
Output: [a] [a b]
func (KeyedCollection[K, V]) WhereBetweenBy ¶
func (c KeyedCollection[K, V]) WhereBetweenBy[E cmp.Ordered](f func(K, V) E, low, high E) KeyedCollection[K, V]
WhereBetweenBy returns the pairs whose key, as f returns it, is from low to high, both included.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"desk": 200, "chair": 80, "door": 100})
fmt.Println(c.WhereBetweenBy(func(_ string, price int) int { return price }, 100, 200).ToMap())
}
Output: map[desk:200 door:100]
func (KeyedCollection[K, V]) WhereInBy ¶
func (c KeyedCollection[K, V]) WhereInBy[E comparable](f func(K, V) E, keys ...E) KeyedCollection[K, V]
WhereInBy returns the pairs whose key, as f returns it, is one of keys.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"desk": 200, "chair": 100, "door": 150})
fmt.Println(c.WhereInBy(func(_ string, price int) int { return price }, 100, 200).ToMap())
}
Output: map[chair:100 desk:200]
func (KeyedCollection[K, V]) WhereInstanceOf ¶
func (c KeyedCollection[K, V]) WhereInstanceOf[U any]() KeyedCollection[K, U]
WhereInstanceOf returns the pairs whose value is of type U, with the value as U. Write U: c.WhereInstanceOf[*Dog]().
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.Of[any](1, "a", 2).Keyed().WhereInstanceOf[int]()
fmt.Println(c.Keys().All(), c.Values().All())
}
Output: [0 2] [1 2]
func (KeyedCollection[K, V]) WhereNotBetweenBy ¶
func (c KeyedCollection[K, V]) WhereNotBetweenBy[E cmp.Ordered](f func(K, V) E, low, high E) KeyedCollection[K, V]
WhereNotBetweenBy returns the pairs whose key, as f returns it, is below low or above high.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"desk": 200, "chair": 80, "door": 100})
fmt.Println(c.WhereNotBetweenBy(func(_ string, price int) int { return price }, 100, 200).ToMap())
}
Output: map[chair:80]
func (KeyedCollection[K, V]) WhereNotInBy ¶
func (c KeyedCollection[K, V]) WhereNotInBy[E comparable](f func(K, V) E, keys ...E) KeyedCollection[K, V]
WhereNotInBy returns the pairs whose key, as f returns it, is none of keys.
Example ¶
package main
import (
"fmt"
"github.com/mpyw/collect"
)
func main() {
c := collect.FromMap(map[string]int{"desk": 200, "chair": 100, "door": 150})
fmt.Println(c.WhereNotInBy(func(_ string, price int) int { return price }, 100, 200).ToMap())
}
Output: map[door:150]
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
Number is the constraint of the values that Collection.SumBy, Collection.AvgBy, Collection.MedianBy, Range and RangeStep compute with.
type Tuple2 ¶
type Tuple2[A, B any] struct { A A B B }
Tuple2 holds a value of each of two collections. Collection.Zip2 and Collection.CrossJoin return them. It is not an Entry: neither value is the key of the other.
type Tuple3 ¶
type Tuple3[A, B, C any] struct { A A B B C C }
Tuple3 holds a value of each of three collections. Collection.Zip3 returns them.
type Tuple4 ¶
type Tuple4[A, B, C, D any] struct { A A B B C C D D }
Tuple4 holds a value of each of four collections. Collection.Zip4 returns them.
type Tuple5 ¶
type Tuple5[A, B, C, D, E any] struct { A A B B C C D D E E }
Tuple5 holds a value of each of five collections. Collection.Zip5 returns them.
Source Files
¶
- after.go
- all.go
- avg_by.go
- before.go
- chunk.go
- chunk_by.go
- chunk_while.go
- collection.go
- combine.go
- concat.go
- contains.go
- count.go
- count_by.go
- cross_join.go
- diff_assoc_by.go
- diff_by.go
- diff_func.go
- diff_keys.go
- doesnt_contain.go
- duplicates_by.go
- each.go
- eager.go
- ensure.go
- entries.go
- every.go
- except.go
- filter.go
- first.go
- first_where.go
- flat_map.go
- flip_by.go
- for_page.go
- get.go
- group_by.go
- has.go
- has_any.go
- has_many.go
- has_sole.go
- implode_by.go
- intersect_assoc_by.go
- intersect_by.go
- intersect_func.go
- intersect_keys.go
- is_empty.go
- is_not_empty.go
- join_by.go
- join_final_by.go
- key_by.go
- keyed.go
- keys.go
- last.go
- map.go
- map_to_groups.go
- map_with_keys.go
- marshal_json_to.go
- max_by.go
- median_by.go
- min_by.go
- mode_by.go
- multiply.go
- must_combine.go
- must_ensure.go
- must_first.go
- must_get.go
- must_last.go
- must_sole.go
- nth.go
- only.go
- pad.go
- partition.go
- percentage.go
- pipe.go
- pipe_through.go
- random.go
- random_n.go
- range.go
- range_step.go
- reduce.go
- reject.go
- remember.go
- replace.go
- reverse.go
- search.go
- seq.go
- shuffle.go
- skip.go
- skip_until.go
- skip_while.go
- slice.go
- sliding.go
- sole.go
- sort_by.go
- sort_by_desc.go
- sort_func.go
- sort_keys_by.go
- sort_keys_by_desc.go
- sort_keys_func.go
- split.go
- split_in.go
- sum_by.go
- take.go
- take_until.go
- take_while.go
- tap_each.go
- times.go
- to_map.go
- union.go
- unique_by.go
- unless.go
- values.go
- when.go
- where_between_by.go
- where_in_by.go
- where_instance_of.go
- where_not_between_by.go
- where_not_in_by.go
- zip2.go
- zip3.go
- zip4.go
- zip5.go