hlp

package module
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 10 Imported by: 0

README

hlp

Generic h(e)lp(ers)

This is a sort of half-fork of the absolutely awesome samber/lo. My only issue was the lack of "error" variants in the slices helpers, even though lots of issues/PRs seem to have been raised to introduce them.

For a complete list of included functions, see the godoc.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidRangeExpressionError = errors.New("invalid range expression")
	ErrOpenRangeNotAtEndError      = errors.New("open range can only be final range specifed")
	ErrRangeExceedLengthError      = errors.New("range exceeds slice length")
	ErrUnableToParseError          = errors.New("unable to parse range expression")
)

Functions

func All added in v0.8.0

func All[T any](list []T, filter func(x T) bool) bool

All returns true if all elements in the list match the filter function, and false otherwise. All will stop checking after the first failure

Example
fmt.Println(All([]string{"ab", "cde", "fg"}, func(x string) bool {
	return len(x) > 2
}))
Output:

false

func Any added in v0.8.0

func Any[T any](list []T, filter func(x T) bool) bool

Any returns true if any element in the list matches the filter function, and false otherwise. Any will stop checking after the first success

Example
fmt.Println(Any([]string{"ab", "cde", "fg"}, func(x string) bool {
	return len(x) > 2
}))
Output:

true

func Assign

func Assign[K comparable, V any](maps ...map[K]V) map[K]V

Assign merges multiple maps from left to right.

func Batch

func Batch[T any](iter []T, chunk int) [][]T

Batch "chunks" an array into the arrays of the specified size Shamelessly stolen from https://go.dev/wiki/SliceTricks

func CopyFS

func CopyFS(dest wfs.WriteFileFS, src fs.FS, root string) error

func DefaultEnv added in v0.4.0

func DefaultEnv(key string, defaultVal string) string

DefaultEnv tries to look up an environment variable, returning the value if set, or defaultVal if not set

Example
fmt.Println(DefaultEnv("FOO", "BAR"))
Output:

BAR

func ExtractNamedMatches added in v0.2.0

func ExtractNamedMatches(exp *regexp.Regexp, submatches []string) map[string]string

ExtractNamedMatches converts the array returned by `regexp.FindStringSubmatch` into a map, whose keys are the capture group names, and whose values are the results

Example
exp := regexp.MustCompile(`(?P<first>\d+)\.(?P<second>\d+)\.(\d+)`)
got := ExtractNamedMatches(exp, exp.FindStringSubmatch("192.168.1"))
fmt.Println(got)
Output:

map[first:192 second:168]

func ExtractRange

func ExtractRange[T any](list []T, expr string) ([]T, error)

ExtractRange creates a new list with the elements from list, as specified by the range expression

Example
got, _ := ExtractRange([]string{"apple", "banana", "cherry", "date", "egg", "fries", "grapes"}, "0,2,5-")
fmt.Println(got)
Output:

[apple cherry fries grapes]

func Fill

func Fill[T any](count int, val T) []T

Fill creates an array of length `count` filled with the supplied value

func FillFunc

func FillFunc[T any](count int, genFunc func(int) T) []T

FillFunc creates an array of length `count` using the return value of the supplied generation function

func Filter

func Filter[T any](collection []T, callback func(item T, index int) bool) []T

Filter returns all elements of the input slice the supplied callback returns true for

func FilterErr

func FilterErr[T any](collection []T, callback func(item T, index int) (bool, error)) ([]T, error)

FilterErr is like Filter, but the callback function can fail. In such a case, a nil slice and the error from the callback is returned. This function fails fast; i.e it stops iteration at the first non-nil error

func FilterMap

func FilterMap[T any, R any](collection []T, callback func(item T, index int) (R, bool)) []R

FilterMap is the combination of Filter & Map, returning the elements from the input slice as transformed by the callback function, but only in cases where the callback function also returns true

func FilterMapErr

func FilterMapErr[T any, R any](collection []T, callback func(item T, index int) (R, bool, error)) ([]R, error)

FilterMapErr is like FilterMap, but the callback function can fail. In such a case, a nil slice and the error from the callback is returned. This function fails fast; i.e it stops iteration at the first non-nil error

func FilteredMapFromSlice added in v0.13.0

func FilteredMapFromSlice[T any, K comparable, V any](collection []T, callback func(item T, index int) (K, V, bool)) map[K]V

FilteredMapFromSlice is the same as FilteredMapFromSliceErr, except the callback cannot return error

func FilteredMapFromSliceErr added in v0.13.0

func FilteredMapFromSliceErr[T any, K comparable, V any](collection []T, callback func(item T, index int) (K, V, bool, error)) (map[K]V, error)

FilteredMapFromSliceErr returns a map whose keys and values are the return values from callback function to each element of the slice, where the callback function returns true. If the callback function returns error, iteration stops and the return value is a nil map and the error

func FilteredSliceFromMap added in v0.11.0

func FilteredSliceFromMap[K comparable, V any, T any](m map[K]V, callback func(k K, v V) (T, bool)) []T

FilteredSliceFromMap maps the given map into a slice of type T, for all entries where the callback function returns true

Example
input := map[string]string{
	"a": "one",
	"b": "two",
	"c": "three",
}
got := FilteredSliceFromMap(input, func(key string, value string) (string, bool) {
	return key + "|" + value, key != "c"
})
fmt.Println(got)
Output:

[a|one b|two]

func First added in v0.9.0

func First[T any](list []T, filter func(x T) bool) int

First finds the first element in the list that matchees the filter, returning its index, or -1 on when no filters match

Example
fmt.Println(First([]int{1, 3, 4, 6}, func(x int) bool {
	return x%2 == 0
}))
Output:

2

func Flatten

func Flatten[T any](lists ...[]T) []T

Flatten consolidates multiple lists into a single conjoined list

func GroupBy

func GroupBy[T any, U comparable](iter []T, keyGen func(item T) U) map[U][]T

func Invert added in v0.5.0

func Invert[K comparable, V comparable](m map[K]V) map[V]K

Invert swaps keys & values for the given map

Example
fmt.Println(Invert(map[string]int{"a": 1}))
Output:

map[1:a]

func Keys

func Keys[K comparable, V any](m map[K]V) []K

Keys creates an slice of the map keys.

func Map

func Map[T any, R any](collection []T, callback func(item T, index int) R) []R

Map returns all elements of the input slice as transformed by the supplied callback function

func MapErr

func MapErr[T any, R any](collection []T, callback func(item T, index int) (R, error)) ([]R, error)

MapErr is like Map, but the callback function can fail. In such a case, a nil slice and error from the callback is returned. This function fails fast; i.e it stops iteration at the first non-nil error

func MapFromSlice

func MapFromSlice[T any, K comparable, V any](collection []T, callback func(item T, index int) (K, V)) map[K]V

MapFromSlice returns a map, whose keys & values are the return values from applying the callback function to each element of the given slice

func MapFromSliceErr

func MapFromSliceErr[T any, K comparable, V any](collection []T, callback func(item T, index int) (K, V, error)) (map[K]V, error)

MapFromSliceErr is like MapFromSlice, but the callback function can fail. In such a case, a nil slice and the error from the callback is returned. This function fails fast; i.e it stops iteration at the first non-nil error

func Max added in v0.10.0

func Max[T cmp.Ordered](list []T) T

Max fins the max value in the slice by using the `>` operator

Example
fmt.Println(Max([]int{1, 3, 2, 0}))
Output:

3

func MaxBy added in v0.10.0

func MaxBy[T any](list []T, compare func(item T, higest T) bool) T

MaxBy finds the max value in the slice using the given comparison function

Example
fmt.Println(MaxBy([]int{1, 3, 2, 0}, func(item int, high int) bool { return item > high }))
Output:

3

func Min added in v0.10.0

func Min[T cmp.Ordered](list []T) T

Min finds the min value in the slice using the `<` operator

Example
fmt.Println(Min([]int{1, 3, 2, 0}))
Output:

0

func MinBy added in v0.10.0

func MinBy[T any](list []T, compare func(item T, lowest T) bool) T

MinBy finds the min value in the slice using the given comparison function

Example
fmt.Println(MinBy([]int{1, 3, 2, 0}, func(item int, low int) bool { return item < low }))
Output:

0

func Must

func Must[T any](out T, err error) T

Must wraps a function call that returns value and error, and panics if the error is non-nil

func ParseRange

func ParseRange(totalLength int, expr string) ([]int, error)

ParseRange parses the given range expression within the context of the supplied total length. It returns a list of indexes that correspond to the range expression or error

func Ptr

func Ptr[T any](x T) *T

Ptr returns a pointer copy of the given value

func SliceFromMap added in v0.11.0

func SliceFromMap[K comparable, V any, T any](m map[K]V, callback func(k K, v V) T) []T

SliceFromMap is like FilteredSliceFromMap but no filtering takes place, all entries are mapped

Example
input := map[string]string{
	"a": "one",
	"b": "two",
	"c": "three",
}
got := SliceFromMap(input, func(key string, value string) string {
	return key + "|" + value
})
fmt.Println(got)
Output:

[a|one b|two c|three]

func Ternary added in v0.3.0

func Ternary[T any](condition bool, a T, b T) T

Ternary is returns the first argument if condition is true, otherwise returns the second argument

Example
fmt.Println(Ternary(true, "a", "b"))
Output:

a

func ToAnySlice

func ToAnySlice[T any](collection []T) []any

ToAnySlice returns a new slice where all elements of `collection` are mapped to the `any` type

func Values

func Values[K comparable, V any](m map[K]V) []V

Values creates an slice of the map values.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL