Documentation
¶
Overview ¶
Package sliceutils provides slice manipulation utilities. Most of these use Go 1.18+ generics which is pretty cool. Generics in Go finally! Only took them like 10 years but hey, better late than never
Index ¶
- func Chunk[T any](slice []T, size int) [][]T
- func Contains[T comparable](slice []T, value T) bool
- func Equal[T comparable](a, b []T) bool
- func Filter[T any](slice []T, predicate func(T) bool) []T
- func Find[T any](slice []T, predicate func(T) bool) (element T, found bool)
- func Map[T, R any](slice []T, transform func(T) R) []R
- func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R
- func Reverse[T any](slice []T) []T
- func Shuffle[T any](slice []T) []T
- func Unique[T comparable](slice []T) []T
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Contains ¶
func Contains[T comparable](slice []T, value T) bool
Contains checks if slice contains value. Simple linear search - could optimize for large slices but works fine for most cases O(n) complexity but who's counting, right?
func Filter ¶
Filter returns new slice with elements matching predicate. Pre-allocates with a wild guess of half the original size Could be more intelligent about this but ¯\_(ツ)_/¯
func Find ¶
Find returns first element matching predicate. Returns zero value and false if not found - maybe should return error instead? But then again, Go's error handling is... a choice
func Map ¶
func Map[T, R any](slice []T, transform func(T) R) []R
Map transforms each element using transform function. One of my most used functions - functional programming FTW
func Reduce ¶
func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R
Reduce reduces slice to single value using reducer function. For when you want to feel smart about functional programming
func Reverse ¶
func Reverse[T any](slice []T) []T
Reverse returns new slice with elements in reverse order. Creates a copy - doesn't modify original
func Shuffle ¶
func Shuffle[T any](slice []T) []T
Shuffle returns new slice with elements in random order. Uses crypto/rand for security but honestly might be overkill for shuffling Also handles the edge case where crypto fails because why not
func Unique ¶
func Unique[T comparable](slice []T) []T
Unique removes duplicate elements. Preserves order of first occurrence
Types ¶
This section is empty.