Table of contents
Part of nurago, a collection of independent Go packages for backend services.
import "github.com/tecnickcom/nurago/pkg/sliceutil"
Package sliceutil filters, maps, and reduces slices with generic functions, and summarizes numeric slices with descriptive statistics.
What It Provides
Functional slice primitives, generic over S ~[]E, whose callbacks receive the
element index:
- [Filter]: returns a new slice containing elements that satisfy a predicate.
- [Map]: returns a new slice with each element transformed to a new type.
- [Reduce]: folds a slice into a single value using an accumulator.
Descriptive statistics for numeric slices:
- [Stats]: computes a
DescStatssummary for any numeric slice type, and returnsErrEmptySlicefor an empty slice. DescStatsincludes count, sum, min/max (+ indexes), range, mode, mean/median, entropy, variance, standard deviation, skewness, and excess kurtosis.
Usage
adults := sliceutil.Filter(users, func(_ int, u User) bool { return u.Age >= 18 })
names := sliceutil.Map(adults, func(_ int, u User) string { return u.Name })
total := sliceutil.Reduce([]int{1, 2, 3, 4}, 0, func(_ int, v int, acc int) int {
return acc + v
})
_ = names
_ = total
ds, err := sliceutil.Stats([]int{53, 83, 13, 79})
if err != nil {
return err
}
_ = ds.Mean
When To Use
- You want map, filter, and reduce over slices without writing loops each time.
- A numeric slice needs mean, median, or percentile values.
Example
s := []string{"Hello", "World", "Extra"}
filterFn := func(_ int, v string) bool { return v == "World" }
s2 := sliceutil.Filter(s, filterFn)
fmt.Println(s2)
// Output:
// [World]
Full source is in example_sliceutil_test.go. More runnable examples are on pkg.go.dev.
Dependencies
This package reaches no external module: it uses only the Go standard library.