A collection of utility functions for Go, inspired by convenient helpers found in Python and JavaScript.
go get github.com/johnwroge/go_helpers
import "github.com/johnwroge/go_helpers"
Min(a, b int)
: Returns the smaller of two integersMax(a, b int)
: Returns the larger of two integersMinInSlice(nums []int)
: Returns the smallest number in a sliceMaxInSlice(nums []int)
: Returns the largest number in a sliceSum(nums []int)
: Returns the sum of all numbers in a sliceAverage(nums []int)
: Calculates the average of numbers in a sliceRoundToDecimals(x float64, decimals int)
: Rounds a float to specified decimal places
Contains[T comparable](slice []T, element T)
: Checks if an element exists in a sliceUnique[T comparable](slice []T)
: Removes duplicate elements from a sliceReverse[T any](slice []T)
: Reverses the order of elements in a sliceShuffle[T any](slice []T)
: Randomly reorders elements in a sliceChunk[T any](slice []T, size int)
: Splits a slice into smaller chunks of specified sizeRange(start, end int)
: Creates a slice of numbers from start to end (exclusive)Intersection[T comparable](a, b []T)
: Returns elements that exist in both slicesUnion[T comparable](a, b []T)
: Returns unique elements from both slices
Map[T, U any](slice []T, f func(T) U)
: Applies a function to each element in a sliceFilter[T any](slice []T, f func(T) bool)
: Returns elements that pass a test functionReduce[T, U any](slice []T, initial U, f func(U, T) U)
: Reduces a slice to a single valueGroupBy[T any, K comparable](slice []T, keyFunc func(T) K)
: Groups slice elements by a key function
Join(elements []string, separator string)
: Joins strings with a separatorSplit(s, separator string, keepEmpty bool)
: Splits a string by separatorIsNumeric(s string)
: Checks if a string contains only numeric characters
Keys[K comparable, V any](m map[K]V)
: Returns all keys from a mapValues[K comparable, V any](m map[K]V)
: Returns all values from a map
// Using Min/Max
min := gohelpers.Min(5, 3) // Returns 3
max := gohelpers.Max(5, 3) // Returns 5
// Using slice operations
nums := []int{1, 2, 2, 3, 3, 4}
unique := gohelpers.Unique(nums) // Returns [1, 2, 3, 4]
// Using Map
doubled := gohelpers.Map([]int{1, 2, 3}, func(x int) int {
return x * 2
}) // Returns [2, 4, 6]
// Using Filter
evens := gohelpers.Filter([]int{1, 2, 3, 4}, func(x int) bool {
return x%2 == 0
}) // Returns [2, 4]
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.