Documentation
¶
Overview ¶
Package collections provides Collection, an ordered list of values carrying a large set of transformations, and LazyCollection, the same vocabulary over a sequence produced one element at a time.
Collect wraps an existing slice; Make, Empty, Times, Range, Wrap and FromJSON build one from scratch. Collection.Lazy, NewLazyCollection and RangeLazy are the lazy counterparts, and LazyCollection.Collect goes back.
Keys ¶
A Collection[T] is a list, so the key of an element is its position, from zero to Count()-1. An operation that is only meaningful when the keys are keys rather than positions takes a map[K]V instead, as a package function. The arr subpackage reads and writes nested maps and slices by "dot" path.
Methods that cannot be methods ¶
A Go method cannot declare a type parameter, so every operation whose result changes the element type -- Map, Pluck, GroupBy, Reduce, Sum and the rest -- is a package function taking the collection as its first argument. That is the only reason any of them is not a method.
Callbacks ¶
A callback handed both the element and its position takes (value T, key int); one that needs only the element takes (value T). A callback that can stop the walk early says so by returning false.
Defaults and errors ¶
A read that may find nothing returns a second bool result rather than taking a default, so the fallback is written at the call site. An operation that can be asked for something impossible returns an error: ErrInvalidArgument, ErrUnexpectedValue, ErrItemNotFound, or a MultipleItemsFoundError carrying the count.
Index ¶
- Variables
- func After[T comparable](c Collection[T], value T) (T, bool)
- func Average[T any, N Number](c Collection[T], value func(item T) N) (float64, bool)
- func Avg[T any, N Number](c Collection[T], value func(item T) N) (float64, bool)
- func Before[T comparable](c Collection[T], value T) (T, bool)
- func CollapseWithKeys[K comparable, V any](c Collection[map[K]V]) map[K]V
- func Combine[K comparable, V any](keys Collection[K], values []V) map[K]V
- func ContainsStrict[T comparable](c Collection[T], value T) bool
- func CountBy[T any, K comparable](c Collection[T], countBy func(value T, key int) K) map[K]int
- func DiffAssoc[K comparable, V comparable](array, items map[K]V) map[K]V
- func DiffAssocUsing[K comparable, V comparable](array, items map[K]V, compare func(a, b K) int) map[K]V
- func DiffKeys[K comparable, V, W any](array map[K]V, items map[K]W) map[K]V
- func DiffKeysUsing[K comparable, V, W any](array map[K]V, items map[K]W, compare func(a, b K) int) map[K]V
- func DoesntContainStrict[T comparable](c Collection[T], value T) bool
- func Dot(c Collection[any]) map[string]any
- func FirstWhere[T any, V cmp.Ordered](c Collection[T], key func(item T) V, operator string, value V) (T, bool)
- func Flip[T comparable](c Collection[T]) map[T]int
- func GroupBy[T any, K comparable](c Collection[T], groupBy func(value T, key int) K) map[K]Collection[T]
- func Head[T any](array []T) (T, bool)
- func IntersectAssoc[K comparable, V comparable](array, items map[K]V) map[K]V
- func IntersectAssocUsing[K comparable, V comparable](array, items map[K]V, compare func(a, b K) int) map[K]V
- func IntersectByKeys[K comparable, V, W any](array map[K]V, items map[K]W) map[K]V
- func KeyBy[T any, K comparable](c Collection[T], keyBy func(value T, key int) K) map[K]T
- func MapToDictionary[T any, K comparable, V any](c Collection[T], callback func(value T, key int) (K, V)) map[K][]V
- func MapToGroups[T any, K comparable, V any](c Collection[T], callback func(value T, key int) (K, V)) map[K]Collection[V]
- func MapWithKeys[T any, K comparable, V any](c Collection[T], callback func(value T, key int) (K, V)) map[K]V
- func Max[T any, V cmp.Ordered](c Collection[T], value func(item T) V) (V, bool)
- func Median[T any, N Number](c Collection[T], value func(item T) N) (float64, bool)
- func MergeRecursive(array, items map[string]any) map[string]any
- func Min[T any, V cmp.Ordered](c Collection[T], value func(item T) V) (V, bool)
- func Mode[T any, N cmp.Ordered](c Collection[T], value func(item T) N) []N
- func Pipe[T, U any](c Collection[T], callback func(collection Collection[T]) U) U
- func PipeInto[T, U any](c Collection[T], into func(collection Collection[T]) U) U
- func Reduce[T, A any](c Collection[T], callback func(carry A, value T, key int) A, initial A) A
- func ReduceSpread[T, A any](c Collection[T], callback func(carry []A, value T, key int) []A, initial ...A) ([]A, error)
- func ReduceWithKeys[T, A any](c Collection[T], callback func(carry A, value T, key int) A, initial A) A
- func ReplaceRecursive(array, items map[string]any) map[string]any
- func Search[T comparable](c Collection[T], value T) (int, bool)
- func Sum[T any, N Number](c Collection[T], value func(item T) N) N
- func Undot(m map[string]any) map[string]any
- func Unwrap[T any](value Collection[T]) []T
- func Value[T, V any](c Collection[T], key func(item T) V) (V, bool)
- type Collection
- func Chunk[T any](c Collection[T], size int) Collection[Collection[T]]
- func ChunkWhile[T any](c Collection[T], callback func(value T, key int, chunk Collection[T]) bool) Collection[Collection[T]]
- func Collapse[T any](c Collection[Collection[T]]) Collection[T]
- func Collect[T any](items []T) Collection[T]
- func CrossJoin[T any](c Collection[T], lists ...[]T) Collection[Collection[T]]
- func Diff[T comparable](c Collection[T], items []T) Collection[T]
- func DiffUsing[T any](c Collection[T], items []T, compare func(a, b T) int) Collection[T]
- func Duplicates[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[K]
- func DuplicatesStrict[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[K]
- func EachSpread(c Collection[[]any], callback func(values ...any) bool) Collection[[]any]
- func Empty[T any]() Collection[T]
- func Ensure[T, U any](c Collection[T]) (Collection[T], error)
- func FlatMap[T, U any](c Collection[T], callback func(value T, key int) []U) Collection[U]
- func Flatten(c Collection[any], depth ...int) Collection[any]
- func FromJSON[T any](text string) (Collection[T], error)
- func Intersect[T comparable](c Collection[T], items []T) Collection[T]
- func IntersectUsing[T any](c Collection[T], items []T, compare func(a, b T) int) Collection[T]
- func Keys[K cmp.Ordered, V any](array map[K]V) Collection[K]
- func Make[T any](items []T) Collection[T]
- func Map[T, U any](c Collection[T], callback func(value T, key int) U) Collection[U]
- func MapInto[T, U any](c Collection[T], into func(value T) U) Collection[U]
- func MapSpread[U any](c Collection[[]any], callback func(values ...any) U) Collection[U]
- func Pluck[T, V any](c Collection[T], value func(item T) V) Collection[V]
- func Range(from, to, step int) Collection[int]
- func Select[T any](c Collection[map[string]T], keys ...string) Collection[map[string]T]
- func Sliding[T any](c Collection[T], size, step int) (Collection[Collection[T]], error)
- func SortBy[T any, V cmp.Ordered](c Collection[T], callback func(value T, key int) V) Collection[T]
- func SortByDesc[T any, V cmp.Ordered](c Collection[T], callback func(value T, key int) V) Collection[T]
- func SortKeys[K cmp.Ordered, V any](array map[K]V) Collection[V]
- func SortKeysDesc[K cmp.Ordered, V any](array map[K]V) Collection[V]
- func SortKeysUsing[K cmp.Ordered, V any](array map[K]V, compare func(a, b K) int) Collection[V]
- func Split[T any](c Collection[T], numberOfGroups int) (Collection[Collection[T]], error)
- func SplitIn[T any](c Collection[T], numberOfGroups int) (Collection[Collection[T]], error)
- func Times[T any](number int, callback func(int) T) Collection[T]
- func Unique[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[T]
- func UniqueStrict[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[T]
- func Where[T any, V cmp.Ordered](c Collection[T], key func(item T) V, operator string, value V) Collection[T]
- func WhereBetween[T any, V cmp.Ordered](c Collection[T], key func(item T) V, from, to V) Collection[T]
- func WhereIn[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
- func WhereInStrict[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
- func WhereInstanceOf[T, U any](c Collection[T]) Collection[T]
- func WhereNotBetween[T any, V cmp.Ordered](c Collection[T], key func(item T) V, from, to V) Collection[T]
- func WhereNotIn[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
- func WhereNotInStrict[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
- func WhereNotNull[T any, V any](c Collection[T], key func(item T) *V) Collection[T]
- func WhereNull[T any, V any](c Collection[T], key func(item T) *V) Collection[T]
- func WhereStrict[T any, V comparable](c Collection[T], key func(item T) V, value V) Collection[T]
- func Wrap[T any](value ...T) Collection[T]
- func Zip[T any](c Collection[T], items ...[]T) Collection[Collection[T]]
- func (c *Collection[T]) Add(item T) *Collection[T]
- func (c Collection[T]) All() []T
- func (c Collection[T]) Collect() Collection[T]
- func (c Collection[T]) Concat(source []T) Collection[T]
- func (c Collection[T]) Contains(callback func(value T, key int) bool) bool
- func (c Collection[T]) ContainsManyItems(callback func(value T, key int) bool) bool
- func (c Collection[T]) ContainsOneItem(callback func(value T, key int) bool) bool
- func (c Collection[T]) Count() int
- func (c Collection[T]) Dd()
- func (c Collection[T]) DoesntContain(callback func(value T, key int) bool) bool
- func (c Collection[T]) Dump() Collection[T]
- func (c Collection[T]) Each(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) Every(callback func(value T, key int) bool) bool
- func (c Collection[T]) Except(keys ...int) Collection[T]
- func (c Collection[T]) Filter(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) First(callback func(value T, key int) bool) (T, bool)
- func (c Collection[T]) FirstOrFail(callback func(value T, key int) bool) (T, error)
- func (c Collection[T]) ForPage(page, perPage int) Collection[T]
- func (c *Collection[T]) Forget(keys ...int) *Collection[T]
- func (c Collection[T]) Get(key int) (T, bool)
- func (c *Collection[T]) GetOrPut(key int, value T) T
- func (c Collection[T]) Has(keys ...int) bool
- func (c Collection[T]) HasAny(keys ...int) bool
- func (c Collection[T]) HasMany(callback func(value T, key int) bool) bool
- func (c Collection[T]) HasSole(callback func(value T, key int) bool) bool
- func (c Collection[T]) Implode(glue string, value func(item T) string) string
- func (c Collection[T]) IsEmpty() bool
- func (c Collection[T]) IsNotEmpty() bool
- func (c Collection[T]) Join(glue, finalGlue string, value func(item T) string) string
- func (c Collection[T]) Keys() Collection[int]
- func (c Collection[T]) Last(callback func(value T, key int) bool) (T, bool)
- func (c Collection[T]) Lazy() LazyCollection[T]
- func (c Collection[T]) Merge(items []T) Collection[T]
- func (c Collection[T]) Multiply(multiplier int) Collection[T]
- func (c Collection[T]) Nth(step, offset int) (Collection[T], error)
- func (c Collection[T]) Only(keys ...int) Collection[T]
- func (c Collection[T]) Pad(size int, value T) Collection[T]
- func (c Collection[T]) Partition(callback func(value T, key int) bool) (passed, failed Collection[T])
- func (c Collection[T]) Percentage(callback func(value T, key int) bool, precision int) (float64, bool)
- func (c Collection[T]) PipeThrough(callbacks ...func(collection Collection[T]) Collection[T]) Collection[T]
- func (c *Collection[T]) Pop(count int) Collection[T]
- func (c *Collection[T]) Prepend(value T) *Collection[T]
- func (c *Collection[T]) Pull(key int) (T, bool)
- func (c *Collection[T]) Push(values ...T) *Collection[T]
- func (c *Collection[T]) Put(key int, value T) *Collection[T]
- func (c Collection[T]) Random(number int) (Collection[T], error)
- func (c Collection[T]) Reject(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) Replace(items map[int]T) Collection[T]
- func (c Collection[T]) Reverse() Collection[T]
- func (c *Collection[T]) Shift(count int) Collection[T]
- func (c Collection[T]) Shuffle() Collection[T]
- func (c Collection[T]) Skip(count int) Collection[T]
- func (c Collection[T]) SkipUntil(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) SkipWhile(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) Slice(offset int, length ...int) Collection[T]
- func (c Collection[T]) Sole(callback func(value T, key int) bool) (T, error)
- func (c Collection[T]) Some(callback func(value T, key int) bool) bool
- func (c Collection[T]) Sort(compare func(a, b T) int) Collection[T]
- func (c Collection[T]) SortDesc(compare func(a, b T) int) Collection[T]
- func (c *Collection[T]) Splice(offset int, length *int, replacement ...T) Collection[T]
- func (c Collection[T]) Take(limit int) Collection[T]
- func (c Collection[T]) TakeUntil(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) TakeWhile(callback func(value T, key int) bool) Collection[T]
- func (c Collection[T]) Tap(callback func(collection Collection[T])) Collection[T]
- func (c Collection[T]) ToArray() []any
- func (c Collection[T]) ToBase() Collection[T]
- func (c Collection[T]) ToJSON() (string, error)
- func (c Collection[T]) ToPrettyJSON() (string, error)
- func (c *Collection[T]) Transform(callback func(T) T) *Collection[T]
- func (c Collection[T]) Union(items []T) Collection[T]
- func (c Collection[T]) Unless(condition bool, ...) Collection[T]
- func (c Collection[T]) UnlessEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) UnlessNotEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
- func (c *Collection[T]) Unshift(values ...T) *Collection[T]
- func (c Collection[T]) Values() Collection[T]
- func (c Collection[T]) When(condition bool, ...) Collection[T]
- func (c Collection[T]) WhenEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
- func (c Collection[T]) WhenNotEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
- type LazyCollection
- func ChunkLazy[T any](l LazyCollection[T], size int) LazyCollection[Collection[T]]
- func MapLazy[T, U any](l LazyCollection[T], callback func(value T, key int) U) LazyCollection[U]
- func NewLazyCollection[T any](source iter.Seq2[int, T]) LazyCollection[T]
- func RangeLazy(from, to, step int) LazyCollection[int]
- func (l LazyCollection[T]) All() []T
- func (l LazyCollection[T]) Collect() Collection[T]
- func (l LazyCollection[T]) Count() int
- func (l LazyCollection[T]) Each(callback func(value T, key int) bool) LazyCollection[T]
- func (l LazyCollection[T]) Eager() LazyCollection[T]
- func (l LazyCollection[T]) Filter(callback func(value T, key int) bool) LazyCollection[T]
- func (l LazyCollection[T]) First(callback func(value T, key int) bool) (T, bool)
- func (l LazyCollection[T]) GetIterator() iter.Seq2[int, T]
- func (l LazyCollection[T]) IsEmpty() bool
- func (l LazyCollection[T]) IsNotEmpty() bool
- func (l LazyCollection[T]) Reject(callback func(value T, key int) bool) LazyCollection[T]
- func (l LazyCollection[T]) Remember() LazyCollection[T]
- func (l LazyCollection[T]) Skip(count int) LazyCollection[T]
- func (l LazyCollection[T]) Take(limit int) LazyCollection[T]
- func (l LazyCollection[T]) TakeUntil(callback func(value T, key int) bool) LazyCollection[T]
- func (l LazyCollection[T]) TakeUntilTimeout(timeout time.Time, callback func(value T, key int)) LazyCollection[T]
- func (l LazyCollection[T]) TakeWhile(callback func(value T, key int) bool) LazyCollection[T]
- func (l LazyCollection[T]) TapEach(callback func(value T, key int)) LazyCollection[T]
- func (l LazyCollection[T]) Throttle(interval time.Duration) LazyCollection[T]
- func (l LazyCollection[T]) WithHeartbeat(interval time.Duration, callback func()) LazyCollection[T]
- type MultipleItemsFoundError
- type Number
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidArgument = errors.New("collections: invalid argument")
ErrInvalidArgument reports an argument a collection operation cannot honour: Nth, Split, SplitIn, Sliding and Random return it.
var ErrItemNotFound = errors.New("collections: item not found")
ErrItemNotFound is returned by Sole and FirstOrFail when no item passes the filter.
var ErrMultipleItemsFound = errors.New("collections: multiple items found")
ErrMultipleItemsFound reports that more than one item passed a filter that admits only one. Sole returns a MultipleItemsFoundError, which unwraps to this sentinel and carries how many were found.
var ErrUnexpectedValue = errors.New("collections: unexpected value")
ErrUnexpectedValue reports a callback that returned something the operation cannot use: ReduceSpread and Ensure return it.
Functions ¶
func After ¶
func After[T comparable](c Collection[T], value T) (T, bool)
After returns the item sitting just after the first one equal to value.
The second result is false when the value is absent or is the last item.
func Average ¶
func Average[T any, N Number](c Collection[T], value func(item T) N) (float64, bool)
Average is Avg.
func Avg ¶
func Avg[T any, N Number](c Collection[T], value func(item T) N) (float64, bool)
Avg returns the mean of the number the projection reads off every element.
The second result is false on an empty collection.
func Before ¶
func Before[T comparable](c Collection[T], value T) (T, bool)
Before returns the item sitting just before the first one equal to value.
The second result is false when the value is absent or is the first item.
func CollapseWithKeys ¶
func CollapseWithKeys[K comparable, V any](c Collection[map[K]V]) map[K]V
CollapseWithKeys flattens the maps in the collection into one, keeping their keys.
A key held by more than one element ends up with the value of the last.
func Combine ¶
func Combine[K comparable, V any](keys Collection[K], values []V) map[K]V
Combine builds a map, this collection supplying the keys and values the values.
Pairing stops at the shorter of the two.
func ContainsStrict ¶
func ContainsStrict[T comparable](c Collection[T], value T) bool
ContainsStrict reports whether any item equals value. It is the search by value, where Contains runs a test.
func CountBy ¶
func CountBy[T any, K comparable](c Collection[T], countBy func(value T, key int) K) map[K]int
CountBy counts how many items fall under each key the callback reads.
func DiffAssoc ¶
func DiffAssoc[K comparable, V comparable](array, items map[K]V) map[K]V
DiffAssoc keeps the entries whose key and value together are absent from items.
An entry survives when items has no such key, or has it with another value. The result is empty rather than nil.
func DiffAssocUsing ¶
func DiffAssocUsing[K comparable, V comparable](array, items map[K]V, compare func(a, b K) int) map[K]V
DiffAssocUsing is DiffAssoc with the keys compared by the callback rather than by ==.
The callback compares keys only; values are still compared by ==. It reports zero when two keys are the same key.
func DiffKeys ¶
func DiffKeys[K comparable, V, W any](array map[K]V, items map[K]W) map[K]V
DiffKeys keeps the entries whose key is absent from items, whatever the values on either side are.
items may hold a different value type, for exactly that reason: only its keys are read.
func DiffKeysUsing ¶
func DiffKeysUsing[K comparable, V, W any](array map[K]V, items map[K]W, compare func(a, b K) int) map[K]V
DiffKeysUsing is DiffKeys with the keys compared by the callback rather than by ==.
func DoesntContainStrict ¶
func DoesntContainStrict[T comparable](c Collection[T], value T) bool
DoesntContainStrict reports whether no item equals value. It is the negation of ContainsStrict, and exists so the absent case reads as its own call rather than as an exclamation mark in front of somebody else's.
func Dot ¶
func Dot(c Collection[any]) map[string]any
Dot flattens the collection into single-level "dot" keys, the top-level key of each element being its position.
func FirstWhere ¶
func FirstWhere[T any, V cmp.Ordered](c Collection[T], key func(item T) V, operator string, value V) (T, bool)
FirstWhere returns the first item whose projected key satisfies the comparison. It is Where followed by First, and takes the same operator set Where documents.
The second result is false when nothing matches, so a zero-valued item is never mistaken for a hit. The whole collection is filtered before the first survivor is taken, so this is a convenience over Where, not a cheaper scan.
func Flip ¶
func Flip[T comparable](c Collection[T]) map[T]int
Flip maps every value to its position.
When a value repeats, the last position wins.
func GroupBy ¶
func GroupBy[T any, K comparable](c Collection[T], groupBy func(value T, key int) K) map[K]Collection[T]
GroupBy gathers the items under the key the callback reads off each one.
Within each group the items keep the order they had in the collection. The keys of a Collection[T] are positions, and a group renumbers them, so the original positions are not preserved.
func Head ¶
Head returns the first element of a slice. The second result is false when the slice is empty.
Over a collection, First with a nil callback is the same thing.
func IntersectAssoc ¶
func IntersectAssoc[K comparable, V comparable](array, items map[K]V) map[K]V
IntersectAssoc keeps the entries items has under the same key with the same value.
func IntersectAssocUsing ¶
func IntersectAssocUsing[K comparable, V comparable](array, items map[K]V, compare func(a, b K) int) map[K]V
IntersectAssocUsing is IntersectAssoc with the keys compared by the callback rather than by ==.
func IntersectByKeys ¶
func IntersectByKeys[K comparable, V, W any](array map[K]V, items map[K]W) map[K]V
IntersectByKeys keeps the entries whose key items also has.
The values kept are this map's, never items'.
func KeyBy ¶
func KeyBy[T any, K comparable](c Collection[T], keyBy func(value T, key int) K) map[K]T
KeyBy keys the items by what the callback reads off each one.
When two items share a key the later one wins.
func MapToDictionary ¶
func MapToDictionary[T any, K comparable, V any](c Collection[T], callback func(value T, key int) (K, V)) map[K][]V
MapToDictionary is MapWithKeys where every key keeps all the values mapped onto it, in order, rather than only the last.
func MapToGroups ¶
func MapToGroups[T any, K comparable, V any](c Collection[T], callback func(value T, key int) (K, V)) map[K]Collection[V]
MapToGroups is MapToDictionary with each bucket wrapped in a collection.
func MapWithKeys ¶
func MapWithKeys[T any, K comparable, V any](c Collection[T], callback func(value T, key int) (K, V)) map[K]V
MapWithKeys builds a map from the key and value the callback returns for every element. A repeated key keeps the last value.
func Max ¶
func Max[T any, V cmp.Ordered](c Collection[T], value func(item T) V) (V, bool)
Max returns the largest value the projection reads.
The second result is false on an empty collection.
func Median ¶
func Median[T any, N Number](c Collection[T], value func(item T) N) (float64, bool)
Median returns the middle of the numbers the projection reads.
With an even count it averages the two middle values. The second result is false on an empty collection.
func MergeRecursive ¶
MergeRecursive merges items into array, descending wherever both sides hold a map under a key.
Where a key is on both sides and either side is not a map, the two values become a []any holding both -- a value already a []any contributes its elements rather than itself, so a list grows across repeated merges.
func Min ¶
func Min[T any, V cmp.Ordered](c Collection[T], value func(item T) V) (V, bool)
Min returns the smallest value the projection reads.
The second result is false on an empty collection.
func Mode ¶
func Mode[T any, N cmp.Ordered](c Collection[T], value func(item T) N) []N
Mode returns the values that occur most often, sorted ascending.
The result is nil on an empty collection.
func Pipe ¶
func Pipe[T, U any](c Collection[T], callback func(collection Collection[T]) U) U
Pipe hands the whole collection to the callback and returns its result.
func PipeInto ¶
func PipeInto[T, U any](c Collection[T], into func(collection Collection[T]) U) U
PipeInto builds a U from the whole collection by handing it to into.
As in MapInto the constructor itself is the argument.
func Reduce ¶
func Reduce[T, A any](c Collection[T], callback func(carry A, value T, key int) A, initial A) A
Reduce folds the elements into a single value, starting from initial and carrying the callback's result forward.
func ReduceSpread ¶
func ReduceSpread[T, A any](c Collection[T], callback func(carry []A, value T, key int) []A, initial ...A) ([]A, error)
ReduceSpread is a reduction that carries several accumulators at once.
A reducer that returns a nil slice stops the fold and is reported as ErrUnexpectedValue.
func ReduceWithKeys ¶
func ReduceWithKeys[T, A any](c Collection[T], callback func(carry A, value T, key int) A, initial A) A
ReduceWithKeys is Reduce, under a name that says the key is passed to the callback.
func ReplaceRecursive ¶
ReplaceRecursive lets items win at every key, except where both sides hold a map or both hold a []any: those descend.
Replacing {"a":[1,2,3]} with {"a":[9]} therefore gives {"a":[9,2,3]} and not {"a":[9]}.
func Search ¶
func Search[T comparable](c Collection[T], value T) (int, bool)
Search returns the index of the first item equal to value. The second result is false when there is none.
func Sum ¶
func Sum[T any, N Number](c Collection[T], value func(item T) N) N
Sum adds the number the projection reads off every element.
It returns the zero of N on an empty collection. There is no form without the projection: over a collection of numbers, pass a function that returns its argument.
func Unwrap ¶
func Unwrap[T any](value Collection[T]) []T
Unwrap gives back the plain slice underneath the collection.
func Value ¶
func Value[T, V any](c Collection[T], key func(item T) V) (V, bool)
Value reads one field off the first item. The second result is false on an empty collection.
Types ¶
type Collection ¶
type Collection[T any] []T
Collection is an ordered list of values, and the key of an element is its index.
It is declared as a slice rather than a struct so that a []T can be handed to it and taken back out without a copy, and so that len, range and the slices package keep working on it.
func Chunk ¶
func Chunk[T any](c Collection[T], size int) Collection[Collection[T]]
Chunk breaks the collection into runs of size elements.
A size below one yields an empty collection rather than looping forever. The last chunk is short when the length does not divide evenly.
func ChunkWhile ¶
func ChunkWhile[T any](c Collection[T], callback func(value T, key int, chunk Collection[T]) bool) Collection[Collection[T]]
ChunkWhile breaks the collection wherever the callback reports false for an element against the chunk built so far, which starts a new chunk.
func Collapse ¶
func Collapse[T any](c Collection[Collection[T]]) Collection[T]
Collapse concatenates the inner collections into one, in order.
func Collect ¶
func Collect[T any](items []T) Collection[T]
Collect wraps items in a Collection. It is the constructor an application actually types.
The result shares the backing array with items: mutate one and the other sees it, up to the point a method reallocates.
func CrossJoin ¶
func CrossJoin[T any](c Collection[T], lists ...[]T) Collection[Collection[T]]
CrossJoin returns the cartesian product of the collection with every list given, one tuple per combination.
The product is folded from a single empty tuple, so crossing nothing wraps each element on its own -- [1,2] becomes [[1],[2]] -- and crossing an empty list yields nothing at all.
It is a function and not a method for the reason Chunk is: instantiating Collection[Collection[T]] from inside a method of Collection[T] is an instantiation cycle, which Go rejects.
func Diff ¶
func Diff[T comparable](c Collection[T], items []T) Collection[T]
Diff keeps the items not present in items.
func DiffUsing ¶
func DiffUsing[T any](c Collection[T], items []T, compare func(a, b T) int) Collection[T]
DiffUsing is Diff with the match decided by compare instead of by ==. compare returns zero for equal, the convention of the cmp and slices packages.
Each item is walked against items until one matches, so the cost is the product of the two lengths where Diff is linear.
func Duplicates ¶
func Duplicates[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[K]
Duplicates reports the keys that appear more than once, in the order their repeats appear. A key seen three times is reported twice.
func DuplicatesStrict ¶
func DuplicatesStrict[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[K]
DuplicatesStrict reports the keys that appear more than once, exactly as Duplicates does. Go's == is already an identity comparison, so the two collapse into one behaviour and this name forwards to Duplicates.
func EachSpread ¶
func EachSpread(c Collection[[]any], callback func(values ...any) bool) Collection[[]any]
EachSpread hands each nested chunk to the callback, spread across its arguments, and returns the collection unchanged.
As in MapSpread the position is appended to the chunk before it is spread. Returning false from the callback stops the walk.
func Empty ¶
func Empty[T any]() Collection[T]
Empty returns an empty collection that is not nil, so that appending to it and comparing its length behave the same as on a collection that had elements.
func Ensure ¶
func Ensure[T, U any](c Collection[T]) (Collection[T], error)
Ensure returns the collection unchanged when every item is a U, and ErrUnexpectedValue naming the first item that is not.
func FlatMap ¶
func FlatMap[T, U any](c Collection[T], callback func(value T, key int) []U) Collection[U]
FlatMap concatenates the slice the callback returns for every element.
func Flatten ¶
func Flatten(c Collection[any], depth ...int) Collection[any]
Flatten squashes a nested structure into one level.
The depth is optional and unlimited when omitted; only the first one is used. A nested value is a []any or a Collection[any]; anything else is a leaf.
func FromJSON ¶
func FromJSON[T any](text string) (Collection[T], error)
FromJSON builds a collection by decoding a JSON array.
Malformed input returns the decoding error, and a JSON null builds an empty collection rather than a nil one. A Collection[T] is a list, so a JSON object is a decoding error here; decode it into a map with encoding/json directly.
func Intersect ¶
func Intersect[T comparable](c Collection[T], items []T) Collection[T]
Intersect keeps the items also present in items.
func IntersectUsing ¶
func IntersectUsing[T any](c Collection[T], items []T, compare func(a, b T) int) Collection[T]
IntersectUsing keeps the items that match something in items, with the match decided by compare instead of by ==. compare returns zero for equal, the convention of the cmp and slices packages.
It is Intersect for element types that == cannot decide, or should not: a struct with a field to ignore, or a name to match without regard to case. Each item is walked against items until one matches, so the cost is the product of the two lengths where Intersect is linear. Reach for it when == cannot answer the question, not by default.
func Keys ¶
func Keys[K cmp.Ordered, V any](array map[K]V) Collection[K]
Keys returns the keys of the map, where the method of the same name on Collection[T] returns the positions of a list.
They come out ascending, which is the order SortKeys puts their values in, so the two walked together pair each value with the key it came from.
func Make ¶
func Make[T any](items []T) Collection[T]
Make wraps items in a Collection, as Collect does.
func Map ¶
func Map[T, U any](c Collection[T], callback func(value T, key int) U) Collection[U]
Map returns the result of the callback for every element, in order.
It is a function and not a method because the callback changes the element type, and a Go method cannot declare a type parameter.
func MapInto ¶
func MapInto[T, U any](c Collection[T], into func(value T) U) Collection[U]
MapInto builds a U from every element by handing it to into.
The constructor itself is the argument: Go cannot reach a type from a name in a string, so there is no class name to pass.
func MapSpread ¶
func MapSpread[U any](c Collection[[]any], callback func(values ...any) U) Collection[U]
MapSpread spreads each nested chunk across the callback's arguments.
The position is appended to the chunk before it is spread, so the callback receives the chunk's elements and then that position. That is why the element type is []any and not []T: the trailing key is an int and the elements need not be.
func Pluck ¶
func Pluck[T, V any](c Collection[T], value func(item T) V) Collection[V]
Pluck reads one field off every element.
The field is named with an accessor rather than a string, because Go cannot reach a field from a name at run time. To key the result by a second field, use MapWithKeys.
func Range ¶
func Range(from, to, step int) Collection[int]
Range counts from from to to, inclusive.
A step of zero is treated as one, and a negative step, or a to below from, counts downwards.
func Select ¶
func Select[T any](c Collection[map[string]T], keys ...string) Collection[map[string]T]
Select reduces every item to the named keys. A key an item does not have is left out rather than filled with the zero value.
func Sliding ¶
func Sliding[T any](c Collection[T], size, step int) (Collection[Collection[T]], error)
Sliding returns a sliding window of size elements, advancing step at a time.
It returns ErrInvalidArgument when size or step is below one. A collection shorter than the window yields no chunk.
func SortBy ¶
func SortBy[T any, V cmp.Ordered](c Collection[T], callback func(value T, key int) V) Collection[T]
SortBy orders the elements by the value the callback reads off each one. The sort is stable.
func SortByDesc ¶
func SortByDesc[T any, V cmp.Ordered](c Collection[T], callback func(value T, key int) V) Collection[T]
SortByDesc is SortBy with the order reversed.
func SortKeys ¶
func SortKeys[K cmp.Ordered, V any](array map[K]V) Collection[V]
SortKeys returns the values of the map ascending by key.
A Go map cannot carry an order, so the ordering is the result rather than a property of it. Keys over the same map gives the keys in the matching order.
func SortKeysDesc ¶
func SortKeysDesc[K cmp.Ordered, V any](array map[K]V) Collection[V]
SortKeysDesc is SortKeys with the order reversed.
func SortKeysUsing ¶
func SortKeysUsing[K cmp.Ordered, V any](array map[K]V, compare func(a, b K) int) Collection[V]
SortKeysUsing returns the values ordered by the callback applied to their keys.
The keys are put in ascending order before the callback sorts them, so that keys the callback calls equal come out in a fixed order instead of the random one Go gives map iteration.
func Split ¶
func Split[T any](c Collection[T], numberOfGroups int) (Collection[Collection[T]], error)
Split deals the elements into numberOfGroups groups, the earlier groups taking the remainder.
It returns ErrInvalidArgument when numberOfGroups is below one.
func SplitIn ¶
func SplitIn[T any](c Collection[T], numberOfGroups int) (Collection[Collection[T]], error)
SplitIn returns chunks of the size that fits numberOfGroups groups, the last one short.
It returns ErrInvalidArgument when numberOfGroups is below one.
func Times ¶
func Times[T any](number int, callback func(int) T) Collection[T]
Times builds a collection of number elements from the callback.
The callback receives 1, 2, ... number, one-based. A number below one yields an empty collection rather than an error, which is what makes Sliding safe to write in terms of it.
func Unique ¶
func Unique[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[T]
Unique drops the items whose key the callback has already produced.
The first item carrying a key is the one kept, and the order of the collection survives.
func UniqueStrict ¶
func UniqueStrict[T any, K comparable](c Collection[T], key func(value T, k int) K) Collection[T]
UniqueStrict drops the repeated keys exactly as Unique does. Go's == is already an identity comparison, so the two collapse into one behaviour and this name forwards to Unique.
func Where ¶
func Where[T any, V cmp.Ordered](c Collection[T], key func(item T) V, operator string, value V) Collection[T]
Where keeps the items whose projected key compares to value under the operator.
The operator is one of "=", "==", "===", "!=", "<>", "!==", ">", ">=", "<" and "<=". An unknown operator matches nothing.
func WhereBetween ¶
func WhereBetween[T any, V cmp.Ordered](c Collection[T], key func(item T) V, from, to V) Collection[T]
WhereBetween keeps the items whose projected key falls in the range. Both ends are included.
func WhereIn ¶
func WhereIn[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
WhereIn keeps the items whose projected key is one of values.
The order of the collection survives, and values is loaded into a set before the scan, so the cost is one pass regardless of how long values is.
func WhereInStrict ¶
func WhereInStrict[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
WhereInStrict keeps the items whose projected key is one of values, exactly as WhereIn does. Go's == is already an identity comparison, so this name forwards to WhereIn.
func WhereInstanceOf ¶
func WhereInstanceOf[T, U any](c Collection[T]) Collection[T]
WhereInstanceOf keeps the items whose dynamic type is U.
func WhereNotBetween ¶
func WhereNotBetween[T any, V cmp.Ordered](c Collection[T], key func(item T) V, from, to V) Collection[T]
WhereNotBetween keeps the items whose projected key falls outside the range: below from, or above to.
Both ends count as inside, so an item sitting exactly on from or on to is dropped. That makes this the exact complement of WhereBetween -- every item is kept by one of the two and by neither twice.
func WhereNotIn ¶
func WhereNotIn[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
WhereNotIn keeps the items whose projected key is absent from values: the complement of WhereIn, and the way to exclude a known set without spelling out the negated predicate.
The order of the collection survives, and values is loaded into a set before the scan, so the cost is one pass regardless of how long values is.
func WhereNotInStrict ¶
func WhereNotInStrict[T any, V comparable](c Collection[T], key func(item T) V, values []V) Collection[T]
WhereNotInStrict keeps the items whose projected key is absent from values, exactly as WhereNotIn does. Go's == is already an identity comparison, so this name forwards to WhereNotIn.
func WhereNotNull ¶
func WhereNotNull[T any, V any](c Collection[T], key func(item T) *V) Collection[T]
WhereNotNull keeps the items whose accessor returns a non-nil pointer, and drops those where the field is absent. It is the complement of WhereNull.
The accessor returns a pointer because a pointer is how a field that may be absent is spelled in Go.
func WhereNull ¶
func WhereNull[T any, V any](c Collection[T], key func(item T) *V) Collection[T]
WhereNull keeps the items whose accessor returns a nil pointer.
The accessor returns a pointer because a pointer is how a field that may be absent is spelled in Go.
func WhereStrict ¶
func WhereStrict[T any, V comparable](c Collection[T], key func(item T) V, value V) Collection[T]
WhereStrict keeps the items whose projected key equals value. It takes no operator: Go's == is already an identity comparison.
func Wrap ¶
func Wrap[T any](value ...T) Collection[T]
Wrap gathers its arguments into a collection: Wrap[int]() is empty, Wrap(1) holds one element, and Wrap(s...) holds the slice.
func Zip ¶
func Zip[T any](c Collection[T], items ...[]T) Collection[Collection[T]]
Zip pairs the collection position by position with the lists given.
A short input is padded with the zero value of T, and the result is as long as the longest input.
It is a function and not a method for the reason CrossJoin is.
func (*Collection[T]) Add ¶
func (c *Collection[T]) Add(item T) *Collection[T]
Add appends one element and returns the receiver.
func (Collection[T]) All ¶
func (c Collection[T]) All() []T
All returns the elements as a plain slice.
The result is never nil: an empty collection gives an empty slice, so that a caller can append to it without checking.
func (Collection[T]) Collect ¶
func (c Collection[T]) Collect() Collection[T]
Collect returns a fresh collection holding the same elements.
func (Collection[T]) Concat ¶
func (c Collection[T]) Concat(source []T) Collection[T]
Concat appends the source to a copy of the collection and leaves the receiver alone, which is where it differs from Push.
func (Collection[T]) Contains ¶
func (c Collection[T]) Contains(callback func(value T, key int) bool) bool
Contains reports whether any element passes the test. To search for a value rather than run a test, use ContainsStrict.
func (Collection[T]) ContainsManyItems ¶
func (c Collection[T]) ContainsManyItems(callback func(value T, key int) bool) bool
ContainsManyItems reports whether at least two elements pass the test. It is HasMany, which is the name to prefer.
func (Collection[T]) ContainsOneItem ¶
func (c Collection[T]) ContainsOneItem(callback func(value T, key int) bool) bool
ContainsOneItem reports whether exactly one element passes the test. A nil callback reads the length instead.
func (Collection[T]) Count ¶
func (c Collection[T]) Count() int
Count reports the number of elements.
func (Collection[T]) Dd ¶
func (c Collection[T]) Dd()
Dd writes the elements to standard output and ends the process with status 1. It never returns, which is why it is not chainable.
func (Collection[T]) DoesntContain ¶
func (c Collection[T]) DoesntContain(callback func(value T, key int) bool) bool
DoesntContain reports whether no element passes the test. It is the negation of Contains.
func (Collection[T]) Dump ¶
func (c Collection[T]) Dump() Collection[T]
Dump writes the elements to standard output and returns the collection, so the call can sit inside a chain.
func (Collection[T]) Each ¶
func (c Collection[T]) Each(callback func(value T, key int) bool) Collection[T]
Each hands every element to the callback in order.
The callback stops the walk by returning false. It returns the collection so the call can be chained.
func (Collection[T]) Every ¶
func (c Collection[T]) Every(callback func(value T, key int) bool) bool
Every reports whether every element passes the test.
An empty collection returns true: there is no element to fail the test.
func (Collection[T]) Except ¶
func (c Collection[T]) Except(keys ...int) Collection[T]
Except returns everything but the elements at the given indices.
func (Collection[T]) Filter ¶
func (c Collection[T]) Filter(callback func(value T, key int) bool) Collection[T]
Filter keeps the elements the callback passes.
A nil callback keeps everything, and the result is empty rather than nil when nothing passes.
func (Collection[T]) First ¶
func (c Collection[T]) First(callback func(value T, key int) bool) (T, bool)
First returns the first element passing the test.
A nil callback returns the first element. The second result is false when the collection is empty or nothing matches, and the first is then the zero value, so the caller writes the fallback at the call site.
func (Collection[T]) FirstOrFail ¶
func (c Collection[T]) FirstOrFail(callback func(value T, key int) bool) (T, error)
FirstOrFail returns the first element passing the test, or ErrItemNotFound when nothing matches.
func (Collection[T]) ForPage ¶
func (c Collection[T]) ForPage(page, perPage int) Collection[T]
ForPage returns the perPage elements of the one-based page.
A page below one reads from the start: the offset is clamped at zero rather than counting backwards. A negative perPage yields nothing.
func (*Collection[T]) Forget ¶
func (c *Collection[T]) Forget(keys ...int) *Collection[T]
Forget removes the elements at the given indices. The survivors close the gap and are renumbered.
func (Collection[T]) Get ¶
func (c Collection[T]) Get(key int) (T, bool)
Get returns the element at the index.
The second result is false when the index is out of range, so the caller supplies the fallback at the call site instead of passing one in.
func (*Collection[T]) GetOrPut ¶
func (c *Collection[T]) GetOrPut(key int, value T) T
GetOrPut returns the element at the index, or writes the value there and returns it when the index is not filled yet.
func (Collection[T]) Has ¶
func (c Collection[T]) Has(keys ...int) bool
Has reports whether every index given is within the collection. With no index it reports false.
func (Collection[T]) HasAny ¶
func (c Collection[T]) HasAny(keys ...int) bool
HasAny reports whether at least one index given is within the collection.
func (Collection[T]) HasMany ¶
func (c Collection[T]) HasMany(callback func(value T, key int) bool) bool
HasMany reports whether at least two elements pass the test.
The walk stops at the second match, which is what makes it cheap on a long collection. A nil callback reads the length instead.
func (Collection[T]) HasSole ¶
func (c Collection[T]) HasSole(callback func(value T, key int) bool) bool
HasSole reports whether exactly one element passes the test.
A nil callback counts the whole collection instead of filtering it.
func (Collection[T]) Implode ¶
func (c Collection[T]) Implode(glue string, value func(item T) string) string
Implode renders each element with value and joins the results with glue.
A nil value renders each element with fmt.Sprint.
func (Collection[T]) IsEmpty ¶
func (c Collection[T]) IsEmpty() bool
IsEmpty reports whether the collection holds no elements.
func (Collection[T]) IsNotEmpty ¶
func (c Collection[T]) IsNotEmpty() bool
IsNotEmpty reports whether the collection holds at least one element.
func (Collection[T]) Join ¶
func (c Collection[T]) Join(glue, finalGlue string, value func(item T) string) string
Join is Implode, except that the last element is attached with finalGlue.
An empty finalGlue is Implode, one element is that element, and no element is the empty string.
func (Collection[T]) Keys ¶
func (c Collection[T]) Keys() Collection[int]
Keys returns the indices of the elements: 0, 1, ... Count()-1.
func (Collection[T]) Last ¶
func (c Collection[T]) Last(callback func(value T, key int) bool) (T, bool)
Last returns the last element passing the test.
A nil callback returns the last element. The second result is false when nothing matches, as in First.
func (Collection[T]) Lazy ¶
func (c Collection[T]) Lazy() LazyCollection[T]
Lazy returns a LazyCollection over the elements of this one.
func (Collection[T]) Merge ¶
func (c Collection[T]) Merge(items []T) Collection[T]
Merge appends items to a copy of the collection. It is Concat.
func (Collection[T]) Multiply ¶
func (c Collection[T]) Multiply(multiplier int) Collection[T]
Multiply returns the elements repeated multiplier times, in order.
A multiplier of zero or less gives an empty collection.
func (Collection[T]) Nth ¶
func (c Collection[T]) Nth(step, offset int) (Collection[T], error)
Nth returns every step-th element, starting at offset.
It returns ErrInvalidArgument when step is below one.
func (Collection[T]) Only ¶
func (c Collection[T]) Only(keys ...int) Collection[T]
Only returns the elements at the given indices, in the collection's order.
An index outside the collection is skipped.
func (Collection[T]) Pad ¶
func (c Collection[T]) Pad(size int, value T) Collection[T]
Pad grows the collection to size elements, filling with value.
A positive size pads on the right and a negative size on the left. A size whose magnitude is not larger than the count returns the elements unchanged.
func (Collection[T]) Partition ¶
func (c Collection[T]) Partition(callback func(value T, key int) bool) (passed, failed Collection[T])
Partition returns the elements passing the test, then the ones failing it.
Neither half is nil, and the two together hold every element exactly once.
func (Collection[T]) Percentage ¶
func (c Collection[T]) Percentage(callback func(value T, key int) bool, precision int) (float64, bool)
Percentage returns the share of elements passing the test, from 0 to 100, rounded to precision decimal places.
The second result is false on an empty collection.
func (Collection[T]) PipeThrough ¶
func (c Collection[T]) PipeThrough(callbacks ...func(collection Collection[T]) Collection[T]) Collection[T]
PipeThrough feeds the collection through the callbacks in order, each one receiving what the previous returned.
Every callback here takes and returns a collection; Pipe is there for the shape that returns something else.
func (*Collection[T]) Pop ¶
func (c *Collection[T]) Pop(count int) Collection[T]
Pop removes the last count elements and returns them, most recent first.
A count of zero or less, or an empty collection, gives an empty result; a count above the length takes everything.
func (*Collection[T]) Prepend ¶
func (c *Collection[T]) Prepend(value T) *Collection[T]
Prepend puts a single value at the front. It is Unshift of one element.
func (*Collection[T]) Pull ¶
func (c *Collection[T]) Pull(key int) (T, bool)
Pull reads the element at the index and removes it. The second result is false when the index is out of range, and nothing is removed then.
func (*Collection[T]) Push ¶
func (c *Collection[T]) Push(values ...T) *Collection[T]
Push appends every value and returns the receiver.
func (*Collection[T]) Put ¶
func (c *Collection[T]) Put(key int, value T) *Collection[T]
Put writes the value at the index and returns the receiver, so that calls chain.
Writing past the end grows the collection with zero values up to that index. A negative index is ignored.
func (Collection[T]) Random ¶
func (c Collection[T]) Random(number int) (Collection[T], error)
Random returns number elements picked at random.
It returns ErrInvalidArgument when number is negative or exceeds the length.
func (Collection[T]) Reject ¶
func (c Collection[T]) Reject(callback func(value T, key int) bool) Collection[T]
Reject is Filter with the predicate negated: it drops the elements the callback passes. A nil callback keeps everything.
func (Collection[T]) Replace ¶
func (c Collection[T]) Replace(items map[int]T) Collection[T]
Replace overwrites the elements at the indices items names, and appends the ones past the end in ascending index order. A negative index is ignored.
func (Collection[T]) Reverse ¶
func (c Collection[T]) Reverse() Collection[T]
Reverse returns the elements in the opposite order.
func (*Collection[T]) Shift ¶
func (c *Collection[T]) Shift(count int) Collection[T]
Shift removes the first count elements and returns them in order. As with Pop, a count of zero or less gives an empty result and a count above the length takes everything.
func (Collection[T]) Shuffle ¶
func (c Collection[T]) Shuffle() Collection[T]
Shuffle returns a copy of the elements in a random order.
It draws from crypto/rand: a shuffle seeded from the clock is a shuffle an attacker can replay. When the draw fails the copy is returned as it stands.
func (Collection[T]) Skip ¶
func (c Collection[T]) Skip(count int) Collection[T]
Skip returns everything past the first count elements.
func (Collection[T]) SkipUntil ¶
func (c Collection[T]) SkipUntil(callback func(value T, key int) bool) Collection[T]
SkipUntil returns everything from the first element passing the test onwards.
func (Collection[T]) SkipWhile ¶
func (c Collection[T]) SkipWhile(callback func(value T, key int) bool) Collection[T]
SkipWhile returns everything from the first element failing the test onwards.
func (Collection[T]) Slice ¶
func (c Collection[T]) Slice(offset int, length ...int) Collection[T]
Slice returns the run of elements starting at offset.
A negative offset counts from the end, and a negative length stops that many elements before the end. Omit length to read to the end; only the first one is used, the variadic standing in for an optional argument.
func (Collection[T]) Sole ¶
func (c Collection[T]) Sole(callback func(value T, key int) bool) (T, error)
Sole returns the one element passing the test.
It returns ErrItemNotFound when nothing matches, and a MultipleItemsFoundError carrying the count when more than one does.
func (Collection[T]) Some ¶
func (c Collection[T]) Some(callback func(value T, key int) bool) bool
Some reports whether any element passes the test. It is Contains.
func (Collection[T]) Sort ¶
func (c Collection[T]) Sort(compare func(a, b T) int) Collection[T]
Sort orders a copy of the elements with compare, which returns zero for equal, the convention of the cmp and slices packages.
The comparison is required, because Go cannot compare an arbitrary T; a nil compare returns the copy unsorted. The sort is stable.
func (Collection[T]) SortDesc ¶
func (c Collection[T]) SortDesc(compare func(a, b T) int) Collection[T]
SortDesc is Sort with the comparison reversed.
func (*Collection[T]) Splice ¶
func (c *Collection[T]) Splice(offset int, length *int, replacement ...T) Collection[T]
Splice removes a run of elements, optionally putting the replacement in its place, and returns what it removed.
It mutates the receiver, which is why it takes a pointer. A nil length cuts to the end; a negative length stops that many elements before it.
func (Collection[T]) Take ¶
func (c Collection[T]) Take(limit int) Collection[T]
Take returns the first limit elements. A negative limit takes that many from the end instead.
func (Collection[T]) TakeUntil ¶
func (c Collection[T]) TakeUntil(callback func(value T, key int) bool) Collection[T]
TakeUntil returns the elements before the first one passing the test.
func (Collection[T]) TakeWhile ¶
func (c Collection[T]) TakeWhile(callback func(value T, key int) bool) Collection[T]
TakeWhile returns the leading run of elements passing the test.
func (Collection[T]) Tap ¶
func (c Collection[T]) Tap(callback func(collection Collection[T])) Collection[T]
Tap hands the collection to the callback and returns it unchanged.
func (Collection[T]) ToArray ¶
func (c Collection[T]) ToArray() []any
ToArray returns the elements as a []any, with each element that knows how to become an array turned into one.
An element with a ToArray method returning []any or map[string]any is converted through it; anything else is passed through as it is.
It differs from All: All hands back the elements with their own type, ToArray hands back []any with the convertible ones already converted.
func (Collection[T]) ToBase ¶
func (c Collection[T]) ToBase() Collection[T]
ToBase returns a detached copy of the collection, as Values does.
func (Collection[T]) ToJSON ¶
func (c Collection[T]) ToJSON() (string, error)
ToJSON encodes the elements as a JSON array, and returns the marshalling error when an element cannot be encoded. For indented output use ToPrettyJSON.
func (Collection[T]) ToPrettyJSON ¶
func (c Collection[T]) ToPrettyJSON() (string, error)
ToPrettyJSON is ToJSON with the output indented by four spaces.
func (*Collection[T]) Transform ¶
func (c *Collection[T]) Transform(callback func(T) T) *Collection[T]
Transform replaces every element with the result of the callback, in place. Unlike Map it cannot change the element type.
func (Collection[T]) Union ¶
func (c Collection[T]) Union(items []T) Collection[T]
Union keeps the receiver's element at every index it has, and appends the tail of items past that length.
func (Collection[T]) Unless ¶
func (c Collection[T]) Unless(condition bool, callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
Unless is When with the condition negated.
func (Collection[T]) UnlessEmpty ¶
func (c Collection[T]) UnlessEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
UnlessEmpty is WhenNotEmpty.
func (Collection[T]) UnlessNotEmpty ¶
func (c Collection[T]) UnlessNotEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
UnlessNotEmpty is WhenEmpty.
func (*Collection[T]) Unshift ¶
func (c *Collection[T]) Unshift(values ...T) *Collection[T]
Unshift puts the values at the front, in the order given, and returns the receiver.
func (Collection[T]) Values ¶
func (c Collection[T]) Values() Collection[T]
Values returns a copy of the elements, detached from the receiver: writing to the result does not reach the collection it came from.
func (Collection[T]) When ¶
func (c Collection[T]) When(condition bool, callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
When runs callback on the collection when condition holds, and otherwise on the other branch.
Either branch may be nil, which returns the collection unchanged.
func (Collection[T]) WhenEmpty ¶
func (c Collection[T]) WhenEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
WhenEmpty is When with the condition that the collection has no elements.
func (Collection[T]) WhenNotEmpty ¶
func (c Collection[T]) WhenNotEmpty(callback, otherwise func(collection Collection[T]) Collection[T]) Collection[T]
WhenNotEmpty is When with the condition that the collection has at least one element.
type LazyCollection ¶
type LazyCollection[T any] struct { // contains filtered or unexported fields }
LazyCollection holds an iter.Seq2 rather than a slice, so the elements are produced one at a time and a source too large for memory never lands in memory.
The sequence is walked afresh on every operation, and nothing between two walks is retained; Remember and Eager are the ways to change that.
The keys are positions, as they are for Collection, and an operation that drops elements renumbers the survivors from zero. Range over one with GetIterator.
The zero value yields nothing, so a LazyCollection is usable before it is assigned.
func ChunkLazy ¶
func ChunkLazy[T any](l LazyCollection[T], size int) LazyCollection[Collection[T]]
ChunkLazy yields the elements in runs of size, each run gathered into a Collection.
A size below one yields nothing rather than looping forever, and the last run is short. Only the run being built is held, so this stays lazy.
Go cannot overload and Chunk is already taken by the eager form, so the receiver's type is the suffix. It is a function and not a method because instantiating LazyCollection[Collection[T]] from a method of LazyCollection[T] is an instantiation cycle, which Go rejects.
func MapLazy ¶
func MapLazy[T, U any](l LazyCollection[T], callback func(value T, key int) U) LazyCollection[U]
MapLazy runs every element through the callback, one at a time.
Go cannot overload and Map is already taken by the eager form, so the receiver's type is the suffix. It is a function and not a method because the callback changes the element type.
func NewLazyCollection ¶
func NewLazyCollection[T any](source iter.Seq2[int, T]) LazyCollection[T]
NewLazyCollection builds a LazyCollection over the sequence.
The sequence must be re-walkable, since every operation calls it again. One that closes over a single-use resource is not, and Remember is the fix there.
func RangeLazy ¶
func RangeLazy(from, to, step int) LazyCollection[int]
RangeLazy counts from from to to, producing the integers one at a time and never all at once.
As in Range, a step of zero counts by one and a negative step, or a to below from, counts downwards: a constructor that cannot fail is worth more than the error.
func (LazyCollection[T]) All ¶
func (l LazyCollection[T]) All() []T
All walks the whole sequence and hands back the elements as a slice.
This is the method that gives up on being lazy, and its result is never nil.
func (LazyCollection[T]) Collect ¶
func (l LazyCollection[T]) Collect() Collection[T]
Collect walks the whole sequence and returns the elements as an eager Collection.
func (LazyCollection[T]) Count ¶
func (l LazyCollection[T]) Count() int
Count walks the whole sequence and counts it.
func (LazyCollection[T]) Each ¶
func (l LazyCollection[T]) Each(callback func(value T, key int) bool) LazyCollection[T]
Each walks the elements now, stopping when the callback returns false, and returns the collection.
func (LazyCollection[T]) Eager ¶
func (l LazyCollection[T]) Eager() LazyCollection[T]
Eager returns a lazy collection backed by a slice that has already been read.
The source is walked once, here, and never again -- which is the point when the source is a query or a file and the collection is about to be walked several times.
func (LazyCollection[T]) Filter ¶
func (l LazyCollection[T]) Filter(callback func(value T, key int) bool) LazyCollection[T]
Filter keeps the elements the callback passes.
As on Collection, a nil callback keeps everything. The survivors are renumbered from zero.
func (LazyCollection[T]) First ¶
func (l LazyCollection[T]) First(callback func(value T, key int) bool) (T, bool)
First returns the first element passing the test, a nil callback returning the first element.
It stops the source at the first match, so it is safe on an endless sequence. The second result is false when nothing matched, as on Collection.
func (LazyCollection[T]) GetIterator ¶
func (l LazyCollection[T]) GetIterator() iter.Seq2[int, T]
GetIterator returns the underlying sequence, so that range works over it. It is the one method every other one here is built on.
The zero value yields an empty sequence rather than nil.
func (LazyCollection[T]) IsEmpty ¶
func (l LazyCollection[T]) IsEmpty() bool
IsEmpty reports whether the sequence yields no element. It reads one element and no more.
func (LazyCollection[T]) IsNotEmpty ¶
func (l LazyCollection[T]) IsNotEmpty() bool
IsNotEmpty reports whether the sequence yields at least one element.
func (LazyCollection[T]) Reject ¶
func (l LazyCollection[T]) Reject(callback func(value T, key int) bool) LazyCollection[T]
Reject is Filter with the predicate negated. A nil callback keeps everything.
func (LazyCollection[T]) Remember ¶
func (l LazyCollection[T]) Remember() LazyCollection[T]
Remember caches the elements as they are enumerated.
Unlike Eager it reads nothing up front. The first walk pulls from the source and fills a cache as it goes; a second walk serves what the first reached from the cache and pulls only past that point. A source that can be consumed once survives being walked twice, as long as the second walk does not run ahead of the first.
The result is not safe for concurrent use: the cache and the puller are shared state behind the closure.
func (LazyCollection[T]) Skip ¶
func (l LazyCollection[T]) Skip(count int) LazyCollection[T]
Skip yields everything past the first count elements, renumbered from zero.
func (LazyCollection[T]) Take ¶
func (l LazyCollection[T]) Take(limit int) LazyCollection[T]
Take returns the first limit elements.
A positive limit stops the source as soon as it has enough, which is what makes it safe on an endless sequence. A limit of zero yields nothing.
A negative limit takes that many from the end, and for that a ring buffer of that size is filled while the whole source goes past -- so it is neither lazy nor safe on an endless sequence. When the source is shorter than the window every element is yielded in order, as Collection.Take does with the same argument.
func (LazyCollection[T]) TakeUntil ¶
func (l LazyCollection[T]) TakeUntil(callback func(value T, key int) bool) LazyCollection[T]
TakeUntil returns the elements before the first one passing the test.
func (LazyCollection[T]) TakeUntilTimeout ¶
func (l LazyCollection[T]) TakeUntilTimeout(timeout time.Time, callback func(value T, key int)) LazyCollection[T]
TakeUntilTimeout yields elements until the deadline passes, then nothing.
The deadline is checked after each element is handed on, so one element is always produced when the deadline is still ahead at the start. When the deadline has already passed nothing is produced at all.
The callback is optional and reports the element the deadline was noticed after. When there was no such element it is called with the zero value and the key -1.
func (LazyCollection[T]) TakeWhile ¶
func (l LazyCollection[T]) TakeWhile(callback func(value T, key int) bool) LazyCollection[T]
TakeWhile returns the leading run of elements passing the test.
func (LazyCollection[T]) TapEach ¶
func (l LazyCollection[T]) TapEach(callback func(value T, key int)) LazyCollection[T]
TapEach hands each element to the callback as it goes past, and passes it on unchanged.
Nothing runs until the result is walked, which is the whole difference from Each.
func (LazyCollection[T]) Throttle ¶
func (l LazyCollection[T]) Throttle(interval time.Duration) LazyCollection[T]
Throttle releases at most one element per interval.
The interval is measured from the moment the element was fetched, and whatever is left of it is slept off after the consumer is done, so a slow consumer is never slowed further.
func (LazyCollection[T]) WithHeartbeat ¶
func (l LazyCollection[T]) WithHeartbeat(interval time.Duration, callback func()) LazyCollection[T]
WithHeartbeat runs the callback every time the interval has passed while the elements go by.
The clock is read per element, so a sequence that stalls calls the callback no more often than the elements arrive. This is not a timer.
type MultipleItemsFoundError ¶
type MultipleItemsFoundError struct {
// Count is how many items passed the filter.
Count int
}
MultipleItemsFoundError is the error Sole returns when more than one item passes the filter, carrying how many did.
It unwraps to ErrMultipleItemsFound, so errors.Is keeps working on the sentinel and errors.As reaches the count.
func (*MultipleItemsFoundError) Error ¶
func (e *MultipleItemsFoundError) Error() string
Error renders the sentinel's message followed by the count.
func (*MultipleItemsFoundError) GetCount ¶
func (e *MultipleItemsFoundError) GetCount() int
GetCount returns how many items passed the filter.
func (*MultipleItemsFoundError) Unwrap ¶
func (e *MultipleItemsFoundError) Unwrap() error
Unwrap reports ErrMultipleItemsFound, so that errors.Is matches the sentinel.
type Number ¶
type Number interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
~float32 | ~float64
}
Number is the set of types Sum can add. It is written out here rather than imported, so that the package carries no dependency for it.
Complex numbers are absent on purpose: admitting them would make the zero value of an empty sum harder to explain than it is worth.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package arr reads and writes nested maps and slices by "dot" path, and carries the list operations that work on untyped data.
|
Package arr reads and writes nested maps and slices by "dot" path, and carries the list operations that work on untyped data. |
|
Package traits is empty, and stays empty.
|
Package traits is empty, and stays empty. |