Documentation
¶
Overview ¶
Package slice provides fluent slice types that can chain functional collection operations.
Mapper[T] is a fluent slice that can chain operations like ToString (map), KeepIf (filter), etc.
Entries[K, V] is a fluent map type for chaining map operations.
Index ¶
- func Asc[T any, S cmp.Ordered](key func(T) S) func(T, T) int
- func Associate[T any, K comparable, V any](ts []T, fn func(T) (K, V)) map[K]V
- func Chunk[T any](ts []T, size int) [][]T
- func Contains[T comparable](ts []T, target T) bool
- func Desc[T any, S cmp.Ordered](key func(T) S) func(T, T) int
- func FanOutAll[T, R any](ctx context.Context, n int, ts []T, fn func(context.Context, T) (R, error)) ([]R, error)
- func FanOutEach[T any](ctx context.Context, n int, ts []T, fn func(context.Context, T) error) []error
- func FanOutEachWeighted[T any](ctx context.Context, capacity int, ts []T, cost func(T) int, ...) []error
- func FanOutWeightedAll[T, R any](ctx context.Context, capacity int, ts []T, cost func(T) int, ...) ([]R, error)
- func FindAs[R, T any](ts []T) option.Option[R]
- func Fold[T, R any](ts []T, initial R, fn func(R, T) R) R
- func IndexOf[T comparable](ts []T, target T) option.Option[int]
- func IsSortedBy[T any, K cmp.Ordered](ts []T, fn func(T) K) bool
- func KeyBy[T any, K comparable](ts []T, fn func(T) K) map[K]T
- func LastIndexOf[T comparable](ts []T, target T) option.Option[int]
- func MaxBy[T any, K cmp.Ordered](ts []T, key func(T) K) (_ option.Option[T])
- func MinBy[T any, K cmp.Ordered](ts []T, key func(T) K) (_ option.Option[T])
- func Partition[T any](ts []T, fn func(T) bool) (Mapper[T], Mapper[T])
- func Reduce[T any](ts []T, fn func(T, T) T) (_ option.Option[T])
- func ToSet[T comparable](ts []T) map[T]bool
- func ToSetBy[T any, K comparable](ts []T, fn func(T) K) map[K]bool
- func Unzip2[T, A, B any](ts []T, fa func(T) A, fb func(T) B) (Mapper[A], Mapper[B])
- func Unzip3[T, A, B, C any](ts []T, fa func(T) A, fb func(T) B, fc func(T) C) (Mapper[A], Mapper[B], Mapper[C])
- func Unzip4[T, A, B, C, D any](ts []T, fa func(T) A, fb func(T) B, fc func(T) C, fd func(T) D) (Mapper[A], Mapper[B], Mapper[C], Mapper[D])
- func Window[T any](ts []T, size int) [][]T
- type Any
- type Bool
- type Byte
- type Entries
- type Error
- type Float32
- type Float64
- type Group
- type Int
- type Mapper
- func Difference[T comparable](a, b []T) Mapper[T]
- func Enumerate[T any](ts []T) Mapper[pair.Pair[int, T]]
- func FanOut[T, R any](ctx context.Context, n int, ts []T, fn func(context.Context, T) (R, error)) Mapper[rslt.Result[R]]
- func FanOutWeighted[T, R any](ctx context.Context, capacity int, ts []T, cost func(T) int, ...) Mapper[rslt.Result[R]]
- func FilterMap[T, R any](ts []T, fn func(T) (R, bool)) Mapper[R]
- func FlatMap[T, R any](ts []T, fn func(T) []R) Mapper[R]
- func Flatten[T any](tss [][]T) Mapper[T]
- func From[T any](ts []T) Mapper[T]
- func FromSet[T comparable](m map[T]bool) Mapper[T]
- func GroupBy[T any, K comparable](ts []T, fn func(T) K) Mapper[Group[K, T]]
- func GroupSame[T comparable](ts []T) Mapper[Group[T, T]]
- func Intersect[T comparable](a, b []T) Mapper[T]
- func Map[T, R any](ts []T, fn func(T) R) Mapper[R]
- func MapAccum[T, R, S any](ts []T, init S, fn func(S, T) (S, R)) (S, Mapper[R])
- func NonEmpty(ts []string) Mapper[string]
- func NonZero[T comparable](ts []T) Mapper[T]
- func PFlatMap[T, R any](ts []T, workers int, fn func(T) []R) Mapper[R]
- func PMap[T, R any](ts []T, workers int, fn func(T) R) Mapper[R]
- func RepeatN[T any](v T, n int) Mapper[T]
- func Scan[T, R any](ts []T, initial R, fn func(R, T) R) Mapper[R]
- func SortBy[T any, K cmp.Ordered](ts []T, fn func(T) K) Mapper[T]
- func SortByDesc[T any, K cmp.Ordered](ts []T, fn func(T) K) Mapper[T]
- func Union[T comparable](a, b []T) Mapper[T]
- func Unique[T comparable](ts []T) Mapper[T]
- func UniqueBy[T any, K comparable](ts []T, fn func(T) K) Mapper[T]
- func Zip[A, B any](as []A, bs []B) Mapper[pair.Pair[A, B]]
- func ZipWith[A, B, R any](as []A, bs []B, fn func(A, B) R) Mapper[R]
- type Rune
- type String
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Associate ¶ added in v0.41.0
func Associate[T any, K comparable, V any](ts []T, fn func(T) (K, V)) map[K]V
Associate builds a map by applying fn to each element to produce a key-value pair. If multiple elements produce the same key, the last one wins. Returns nil for nil or empty input.
func Chunk ¶ added in v0.28.0
Chunk splits ts into sub-slices of at most size elements. The last chunk may have fewer than size elements.
Each chunk is a sub-slice of ts, so element mutations through a chunk are visible through ts (and vice versa). Capacity is clipped to chunk length, so appending to a chunk allocates a new backing array rather than corrupting adjacent chunks or the source.
Panics if size <= 0.
func Contains ¶ added in v0.28.0
func Contains[T comparable](ts []T, target T) bool
Contains returns true if ts contains target.
func FanOutAll ¶ added in v0.41.0
func FanOutAll[T, R any](ctx context.Context, n int, ts []T, fn func(context.Context, T) (R, error)) ([]R, error)
FanOutAll applies fn to each element concurrently (at most n goroutines), returning all values if every call succeeds, or the first observed failure otherwise. On success, output order matches input order. On first failure (error or panic), the derived context is cancelled so cooperative work can stop early. Already-running callbacks continue until fn returns.
The returned error is the first failure observed (by time, not index). Sibling context.Canceled errors from cancellation do not mask the root cause. Panics in fn are captured as *rslt.PanicError with the original stack trace.
Derives a child context internally — the caller's context is never cancelled.
Panics if n <= 0, ctx is nil, or fn is nil.
func FanOutEach ¶ added in v0.41.0
func FanOutEach[T any](ctx context.Context, n int, ts []T, fn func(context.Context, T) error) []error
FanOutEach applies fn to each element of ts concurrently with at most n goroutines. It is the side-effect variant of FanOut for operations that don't produce values.
Returns []error with len == len(ts). Nil entries indicate success. Panics from fn are wrapped as *rslt.PanicError in the error slice, detectable via errors.As.
Panics if n <= 0, ctx is nil, or fn is nil.
func FanOutEachWeighted ¶ added in v0.41.0
func FanOutEachWeighted[T any](ctx context.Context, capacity int, ts []T, cost func(T) int, fn func(context.Context, T) error) []error
FanOutEachWeighted applies fn to each element of ts concurrently, bounded by a total cost budget. It is the side-effect variant of FanOutWeighted.
Returns []error with len == len(ts). Nil entries indicate success. Panics from fn are wrapped as *rslt.PanicError in the error slice, detectable via errors.As.
Same cost pre-validation semantics as FanOutWeighted: cost is evaluated eagerly, should be pure, and panics in cost propagate immediately.
Panics if capacity <= 0, cost is nil, ctx is nil, or fn is nil. Per-item: panics if cost(t) <= 0 or cost(t) > capacity.
func FanOutWeightedAll ¶ added in v0.41.0
func FanOutWeightedAll[T, R any](ctx context.Context, capacity int, ts []T, cost func(T) int, fn func(context.Context, T) (R, error)) ([]R, error)
FanOutWeightedAll applies fn to each element concurrently, bounded by a total cost budget, returning all values if every call succeeds, or the first observed failure otherwise. On first failure (error or panic), the derived context is cancelled so cooperative work can stop early.
Same error/cancellation semantics as FanOutAll. Same cost pre-validation semantics as FanOutWeighted: cost is evaluated eagerly, should be pure, and panics in cost propagate immediately.
Derives a child context internally — the caller's context is never cancelled.
Panics if capacity <= 0, cost is nil, ctx is nil, or fn is nil. Per-item: panics if cost(t) <= 0 or cost(t) > capacity.
func FindAs ¶ added in v0.21.0
FindAs returns the first element that type-asserts to R, or not-ok if none match. Useful for finding a specific concrete type in a slice of interfaces.
func Fold ¶ added in v0.6.0
func Fold[T, R any](ts []T, initial R, fn func(R, T) R) R
Fold reduces a slice to a single value by applying fn to each element. It starts with initial and applies fn(accumulator, element) for each element from left to right. Returns initial if the slice is empty.
func IndexOf ¶ added in v0.41.0
func IndexOf[T comparable](ts []T, target T) option.Option[int]
IndexOf returns the index of the first occurrence of target, or not-ok if absent. Uses == comparison; for predicate-based search, use IndexWhere.
func IsSortedBy ¶ added in v0.41.0
IsSortedBy reports whether ts is sorted in ascending order by the key extracted via fn.
func KeyBy ¶ added in v0.38.0
func KeyBy[T any, K comparable](ts []T, fn func(T) K) map[K]T
KeyBy indexes elements by a key derived from fn, returning a map from key to element. If multiple elements produce the same key, the last one wins. For common key types, prefer the method forms KeyByString and KeyByInt on Mapper.
func LastIndexOf ¶ added in v0.41.0
func LastIndexOf[T comparable](ts []T, target T) option.Option[int]
LastIndexOf returns the index of the last occurrence of target, or not-ok if absent. Uses == comparison; for predicate-based search, use LastIndexWhere.
func MaxBy ¶ added in v0.41.0
MaxBy returns the element with the largest key, or not-ok if the slice is empty. Keys are compared using cmp.Compare, which places NaN before -Inf for float types. If multiple elements share the largest key, the first one is returned. The key function is called exactly once per element.
func MinBy ¶ added in v0.41.0
MinBy returns the element with the smallest key, or not-ok if the slice is empty. Keys are compared using cmp.Compare, which places NaN before -Inf for float types. If multiple elements share the smallest key, the first one is returned. The key function is called exactly once per element.
func Partition ¶ added in v0.36.0
Partition splits ts into two slices: elements where fn returns true, and elements where it returns false. Input order is preserved in both results. Single pass. Both results are independent slices.
func Reduce ¶ added in v0.41.0
Reduce combines elements left-to-right using the first element as the initial value. Returns not-ok if the slice is empty. For a single-element slice, returns that element without calling fn. Unlike Fold, Reduce requires the result type to match the element type. Nil fn does not panic when the slice has fewer than two elements (fn is never invoked).
func ToSet ¶ added in v0.23.0
func ToSet[T comparable](ts []T) map[T]bool
ToSet returns a map with each element as a key set to true. Requires comparable elements.
func ToSetBy ¶ added in v0.28.0
func ToSetBy[T any, K comparable](ts []T, fn func(T) K) map[K]bool
ToSetBy returns a map with each element's key (extracted by fn) set to true. Useful when elements aren't directly comparable but have a comparable key field.
func Unzip2 ¶ added in v0.6.0
Unzip2 extracts two slices from ts in a single pass by applying the extraction functions. This is more efficient than calling two separate mapping operations when you need multiple fields.
func Unzip3 ¶ added in v0.6.0
func Unzip3[T, A, B, C any](ts []T, fa func(T) A, fb func(T) B, fc func(T) C) (Mapper[A], Mapper[B], Mapper[C])
Unzip3 extracts three slices from ts in a single pass by applying the extraction functions.
func Unzip4 ¶ added in v0.6.0
func Unzip4[T, A, B, C, D any](ts []T, fa func(T) A, fb func(T) B, fc func(T) C, fd func(T) D) (Mapper[A], Mapper[B], Mapper[C], Mapper[D])
Unzip4 extracts four slices from ts in a single pass by applying the extraction functions.
func Window ¶ added in v0.41.0
Window returns sliding windows of size elements. Each window is a sub-slice sharing the backing array of ts — overlapping windows alias the same memory. Mutating an element in one window affects all windows that include that position. Capacity is clipped to window size, so append on a window will not corrupt adjacent windows or the source. Use Clone() on individual windows if you need fully independent copies. Panics if size <= 0. Returns empty for empty/nil input or when len(ts) < size.
Types ¶
type Group ¶ added in v0.35.0
type Group[K comparable, T any] struct { Key K Items []T }
Group holds a grouping key and its collected items.
func (Group[K, T]) GetItems ¶ added in v0.41.0
func (g Group[K, T]) GetItems() []T
GetItems returns the group's items.
type Int ¶
func RangeFrom ¶ added in v0.41.0
RangeFrom returns [start, start+1, ..., end-1]. Returns empty for start >= end. Panics if the range is too large to allocate.
type Mapper ¶
Type aliases for types defined in internal/base. All methods defined on the base types are available through these aliases.
func Difference ¶ added in v0.41.0
func Difference[T comparable](a, b []T) Mapper[T]
Difference returns elements in a that are not in b, deduplicated, preserving first-occurrence order from a.
func Enumerate ¶ added in v0.41.0
Enumerate pairs each element with its zero-based index. Preserves input order. Returns nil for nil input.
func FanOut ¶ added in v0.41.0
func FanOut[T, R any](ctx context.Context, n int, ts []T, fn func(context.Context, T) (R, error)) Mapper[rslt.Result[R]]
FanOut applies fn to each element of ts concurrently with at most n goroutines. Each element gets its own goroutine (semaphore-bounded), enabling per-item scheduling suited for I/O-bound workloads with variable latency.
Returns Mapper[rslt.Result[R]] with len == len(ts), where output[i] corresponds to ts[i].
Panics in fn are recovered and returned as *rslt.PanicError in the result slot, detectable via errors.As. Panics are not re-thrown.
Cancellation guarantees:
- FanOut returns only after all started callbacks have returned. No goroutine leaks.
- At most n callbacks execute concurrently. Semaphore enforced.
- When ctx is cancelled, the scheduler stops launching new work promptly. Unscheduled items get Err(ctx.Err()). Due to check-then-act races, at most one additional callback may start after cancellation occurs.
- In-flight callbacks continue until fn returns.
- Callbacks may observe an already-cancelled context.
- An already-cancelled ctx before FanOut entry: zero callbacks run.
- fn errors do NOT cancel siblings. The caller controls fail-fast by cancelling ctx in fn.
Panics if n <= 0, ctx is nil, or fn is nil.
func FanOutWeighted ¶ added in v0.41.0
func FanOutWeighted[T, R any](ctx context.Context, capacity int, ts []T, cost func(T) int, fn func(context.Context, T) (R, error)) Mapper[rslt.Result[R]]
FanOutWeighted applies fn to each element of ts concurrently, bounded by a total cost budget rather than a fixed item count. Each item's cost is determined by the cost function, and at most capacity units of cost run concurrently.
Returns Mapper[rslt.Result[R]] with len == len(ts), where output[i] corresponds to ts[i].
Panics in fn are recovered and returned as *rslt.PanicError in the result slot, detectable via errors.As. Panics are not re-thrown.
Same cancellation guarantees as FanOut. Partial acquire rollback: if ctx cancels after acquiring some tokens for an item, the scheduler releases them and fills remaining items with ctx.Err().
Items are scheduled in input order. A high-cost item blocks later items from starting even if capacity is available for them (head-of-line blocking).
All item costs are evaluated eagerly before any goroutines start. cost should be pure and inexpensive. If cost panics, the panic propagates immediately (it is not recovered into a result slot). This pre-validation ensures invalid costs are detected before work begins, preserving cleanup guarantees.
Panics if capacity <= 0, cost is nil, ctx is nil, or fn is nil. Per-item: panics if cost(t) <= 0 or cost(t) > capacity.
func FilterMap ¶ added in v0.41.0
FilterMap applies fn to each element and keeps only the results where fn returns true. It combines filtering and type-changing transformation in a single pass. The inclusion decision and transformed output are derived from a single callback invocation per element. Preserves input order among kept elements. Returns nil for nil input.
func FlatMap ¶ added in v0.41.0
FlatMap applies fn to each element of ts and flattens the results into a single slice. It is a standalone function because Go methods cannot introduce new type parameters — the target type R must be inferred from the function argument rather than bound on the receiver.
func Flatten ¶ added in v0.41.0
Flatten concatenates nested slices into a single flat slice, preserving element order.
func FromSet ¶ added in v0.30.0
func FromSet[T comparable](m map[T]bool) Mapper[T]
FromSet extracts the members of a set (keys where value is true) as a Mapper. Order is not guaranteed (map iteration order).
func GroupBy ¶ added in v0.30.0
func GroupBy[T any, K comparable](ts []T, fn func(T) K) Mapper[Group[K, T]]
GroupBy groups elements by the key returned by fn. Groups preserve first-seen key order; items within each group preserve input order.
func GroupSame ¶ added in v0.41.0
func GroupSame[T comparable](ts []T) Mapper[Group[T, T]]
GroupSame groups elements by their own value, returning a group per distinct value. Equivalent to GroupBy with an identity key extractor.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/binaryphile/fluentfp/slice"
)
func main() {
type G = slice.Group[string, string]
// formatGroup formats a group as "value(count)".
formatGroup := func(g G) string {
return fmt.Sprintf("%s(%d)", g.Key, g.Len())
}
statuses := slice.Mapper[string]{"running", "exited", "running", "running"}
formatted := slice.GroupSame(statuses).ToString(formatGroup)
fmt.Println(strings.Join(formatted, ", "))
}
Output: running(3), exited(1)
func Intersect ¶ added in v0.41.0
func Intersect[T comparable](a, b []T) Mapper[T]
Intersect returns elements present in both a and b, deduplicated, preserving first-occurrence order from a.
func Map ¶ added in v0.30.0
Map returns the result of applying fn to each member of ts. It is a standalone function because Go methods cannot introduce new type parameters — the target type R must be inferred from the function argument rather than bound on the receiver.
func MapAccum ¶ added in v0.25.0
MapAccum threads state through a slice, producing both a final state and a mapped output. fn receives the accumulated state and current element, returning new state and an output value. Returns init and an empty slice if ts is empty.
func NonZero ¶ added in v0.41.0
func NonZero[T comparable](ts []T) Mapper[T]
NonZero removes zero-value elements from ts.
func PFlatMap ¶ added in v0.41.0
PFlatMap applies fn to each element of ts concurrently using the specified number of worker goroutines, then flattens the results into a single slice. Order is preserved. The fn must be safe for concurrent use.
It is a standalone function because Go methods cannot introduce new type parameters — the target type R must be inferred from the function argument rather than bound on the receiver.
Panics in fn are recovered, converted to *rslt.PanicError with a stack captured during recovery, and re-panicked on the calling goroutine after all workers exit.
Panics if workers <= 0.
func PMap ¶ added in v0.41.0
PMap returns the result of applying fn to each member of ts, using the specified number of worker goroutines. Order is preserved. The fn must be safe for concurrent use.
Panics in fn are recovered, converted to *rslt.PanicError with a stack captured during recovery, and re-panicked on the calling goroutine after all workers exit.
Panics if workers <= 0.
Example ¶
package main
import (
"fmt"
"runtime"
"github.com/binaryphile/fluentfp/slice"
)
func main() {
double := func(n int) int { return n * 2 }
result := slice.PMap(slice.From([]int{1, 2, 3, 4, 5}), runtime.GOMAXPROCS(0), double)
fmt.Println([]int(result))
}
Output: [2 4 6 8 10]
func Scan ¶ added in v0.41.0
Scan reduces a slice like Fold, but collects all intermediate accumulator values. It includes the initial value as the first element (Haskell scanl semantics), so the result has len(ts)+1 elements. Returns [initial] for an empty or nil slice. Law: the last element equals Fold(ts, initial, fn).
func SortBy ¶ added in v0.23.0
SortBy returns a sorted copy of ts, ordered ascending by the key extracted via fn. The sort is not stable; elements with equal keys may be reordered. fn may be called multiple times per element; it should be pure and inexpensive.
func SortByDesc ¶ added in v0.23.0
SortByDesc returns a sorted copy of ts, ordered descending by the key extracted via fn. The sort is not stable; elements with equal keys may be reordered. fn may be called multiple times per element; it should be pure and inexpensive.
func Union ¶ added in v0.41.0
func Union[T comparable](a, b []T) Mapper[T]
Union returns the deduplicated combination of a and b, preserving first-occurrence order (all of a first, then extras from b).
func Unique ¶ added in v0.41.0
func Unique[T comparable](ts []T) Mapper[T]
Unique removes duplicate elements, preserving first occurrence. For non-comparable types or key-based deduplication, use UniqueBy. Note: for float types, NaN != NaN, so NaN values are never deduplicated. Returns nil for nil input.
func UniqueBy ¶ added in v0.28.0
func UniqueBy[T any, K comparable](ts []T, fn func(T) K) Mapper[T]
UniqueBy returns a new slice with duplicate elements removed, where duplicates are determined by the key returned by fn. Preserves first occurrence and maintains order.
Source Files
¶
- associate.go
- chunk.go
- contains.go
- difference.go
- doc.go
- enumerate.go
- fanout.go
- filter_map.go
- flatmap.go
- flatten.go
- fold.go
- from_set.go
- group.go
- group_by.go
- index_of.go
- intersect.go
- key_by.go
- map.go
- mapaccum.go
- mapper.go
- min_max.go
- nonzero.go
- parallel.go
- partition.go
- pflatmap.go
- range.go
- reduce.go
- repeat.go
- scan.go
- sort.go
- tally.go
- to_set.go
- to_set_by.go
- types.go
- union.go
- unique.go
- unique_by.go
- unzip.go
- window.go
- zip.go