zeroflucs generics
When writing Go code for Go 1.17 or below, we've all written more than our fair share of methods to check "does this slice contain a thing", or "give me the first item matching a predicate". This package contains a roll-up of helpers and methods, as well as generic collection types that enable a lot of this boilerplate code to be removed.
Key attributes:
- Context support for filters/mappers (Optional)
- Does not mutate input during operation.
All code is covered 100% by tests for expected behaviour. Where filters or mappers are used methods are provided with and without context support.
Aggregations
Min
Returns the minimum value from the input slice. Returns 0 if no values.
Max
Returns the maximum value from the input slice. Returns 0 if no values.
Sum
Returns the total sum of the values. Note that when handling large values, you may overflow your input type.
Error Checking
Must
Returns the first value in a pair of (T, error) if there is no error. Otherwise will panic.
Slice Operations
All / AllContext
Returns true if all items in the slice match the filter. Will return true for an empty slice as no items fail the predicate.
Any / AnyContext
Returns true if any item in the slice matches the filter.
Concatenate
Joins N slices of items together in the given order.
Contains
Returns true if the slice contains the specified value T, false otherwise. Uses standard equality operator to compare types.
DefaultIfEmpty
Given a slice, if the slice is empty or nil will create a slice of a single default item.
Filter / FilterContext
Creates a filtered set of the values in the slice, using a filter function.
First
Returns the first item of the slice, or panics if the slice is empty. Use with DefaultIfEmpty to ensure panic-free operation over lists that are potentially empty.
FirstOrDefault
Returns the first item of the slice, or if the slice is empty returns a default value.
Group
Uses a mapper function to assign input values to buckets.
Last
Returns the last item of the slice, or panics if the slice is empty. Use with DefaultIfEmpty to ensure panic-free operation over lists that are potentially empty.
LastOrDefault
Returns the last item of the slice, or a default if the slice is empty.
Map / MapContext
Runs the specified mapper over each element of the input slice, creating an output slice of a different type.
Reverse
Creates a reverse-sorted version of the input slice.
Skip
Skip the first N elements of the slice.
Take
Take the next N elements of the slice.
ToMap / ToMapContext
Converts a slice of values to Go map, using mappers for the key and values respectively.