Documentation
¶
Overview ¶
Package collections provides generic utilities for working with collections like slices, maps, sets, and priority queues.
The package leverages Go generics to provide type-safe operations without runtime overhead. It includes utilities for common operations like filtering, mapping, grouping, and set operations.
Slice Operations:
numbers := []int{1, 2, 3, 4, 5}
evens := collections.Filter(numbers, func(n int) bool { return n%2 == 0 })
squares := collections.Map(numbers, func(n int) int { return n * n })
Map Operations:
data := map[string]int{"a": 1, "b": 2}
keys := collections.Keys(data)
values := collections.Values(data)
Set Operations:
set1 := collections.NewSet(1, 2, 3)
set2 := collections.NewSet(2, 3, 4)
union := set1.Union(set2) // {1, 2, 3, 4}
intersect := set1.Intersect(set2) // {2, 3}
Index ¶
- func Append[T any](slices ...[]T) []T
- func Contains[T comparable](a []T, x T) bool
- func Dedup[T comparable](arr []T) []T
- func DeleteEmptyStrings(s []string) []string
- func Find(a []string, x string) int
- func IniToMap(path string) map[string]string
- func IsExclusionOnlyPatterns(patterns []string) bool
- func KeyValueSliceToMap(in []string) map[string]string
- func MapKeys[K comparable, T any](m map[K]T) []K
- func MapToIni(Map map[string]string) string
- func MatchItems(item string, patterns ...string) bool
- func MergeMap[T1 comparable, T2 any](a, b map[T1]T2) map[T1]T2
- func MergeStructs[T any](base, patch T) (T, error)
- func ReplaceAllInSlice(a []string, find string, replacement string) (replaced []string)
- func SelectorToMap(selector string) (matchLabels map[string]string)
- func SortedMap(m map[string]string) string
- func SplitAllInSlice(a []string, split string, index int) (replaced []string)
- func StructToIni(s interface{}) string
- func StructToJSON(v any) (string, error)
- func StructToMap(s interface{}) map[string]interface{}
- func ToBase64Map(m map[string]interface{}) map[string]string
- func ToByteMap(m map[string]interface{}) map[string][]byte
- func ToGenericMap(m map[string]string) map[string]interface{}
- func ToJSONMap(s any) (map[string]any, error)
- func ToString(i interface{}) string
- func ToStringMap(m map[string]interface{}) map[string]string
- type Equals
- type MetricsOpts
- type Queue
- func (queue *Queue[T]) Clear()
- func (queue *Queue[T]) Dequeue() (T, bool)
- func (queue *Queue[T]) Empty() bool
- func (queue *Queue[T]) Enqueue(value T)
- func (queue *Queue[T]) EnqueueWithDelay(value T, delay time.Duration)
- func (queue *Queue[T]) Iterator() iter.Seq[T]
- func (queue *Queue[T]) Peek() (value T, ok bool)
- func (queue *Queue[T]) Size() int
- func (queue *Queue[T]) String() string
- func (queue *Queue[T]) Values() []T
- type QueueOpts
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Append ¶ added in v1.12.0
func Append[T any](slices ...[]T) []T
Append concatenates multiple slices of strings into a single slice.
func Contains ¶ added in v1.5.1
func Contains[T comparable](a []T, x T) bool
Contains checks if a slice contains the specified element.
Example:
nums := []int{1, 2, 3, 4, 5}
if collections.Contains(nums, 3) {
// Element found
}
func Dedup ¶ added in v1.10.0
func Dedup[T comparable](arr []T) []T
Dedup removes duplicate elements from a slice while preserving order. Returns a new slice containing only the first occurrence of each element.
Example:
nums := []int{1, 2, 2, 3, 1, 4}
unique := collections.Dedup(nums) // [1, 2, 3, 4]
func DeleteEmptyStrings ¶ added in v1.10.0
func Find ¶ added in v1.5.1
Find returns the index of the first occurrence of x in the slice, or len(a) if x is not found.
Example:
fruits := []string{"apple", "banana", "orange"}
idx := collections.Find(fruits, "banana") // Returns 1
func IsExclusionOnlyPatterns ¶ added in v1.36.1
func KeyValueSliceToMap ¶ added in v1.6.3
KeyValueSliceToMap converts a slice of "key=value" strings to a map. Strings without '=' are treated as keys with empty values.
Example:
args := []string{"env=prod", "debug=true", "verbose"}
config := collections.KeyValueSliceToMap(args)
// Result: {"env": "prod", "debug": "true", "verbose": ""}
func MapKeys ¶ added in v1.11.0
func MapKeys[K comparable, T any](m map[K]T) []K
MapKeys returns a slice containing all keys from the map. The order of keys is non-deterministic.
Example:
users := map[int]string{1: "Alice", 2: "Bob", 3: "Charlie"}
ids := collections.MapKeys(users) // [1, 2, 3] (order may vary)
func MapToIni ¶
MapToIni converts a map to INI format with one key=value pair per line.
Example:
config := map[string]string{"host": "localhost", "port": "8080"}
ini := collections.MapToIni(config)
// Result: "host=localhost\nport=8080\n"
func MatchItems ¶ added in v1.6.4
matchItems returns true if any of the patterns in the list match the item. negative matches are supported by prefixing the item with a "!" and takes precendence over positive match. * matches everything to match prefix and suffix use "*" accordingly.
func MergeMap ¶ added in v1.6.3
func MergeMap[T1 comparable, T2 any](a, b map[T1]T2) map[T1]T2
MergeMap merges two maps, with values from b taking precedence. Returns the merged map (modifies map a in place).
Example:
defaults := map[string]int{"timeout": 30, "retries": 3}
overrides := map[string]int{"timeout": 60}
config := collections.MergeMap(defaults, overrides)
// Result: {"timeout": 60, "retries": 3}
func MergeStructs ¶ added in v1.10.0
MergeStructs merges two structs where patch is applied on top of base
func ReplaceAllInSlice ¶
ReplaceAllInSlice applies strings.ReplaceAll to each element in the slice.
Example:
urls := []string{"http://api.com", "http://web.com"}
secure := collections.ReplaceAllInSlice(urls, "http://", "https://")
// Result: ["https://api.com", "https://web.com"]
func SelectorToMap ¶ added in v1.22.0
SelectorToMap parses a comma-separated selector string into a map. Commonly used for Kubernetes-style label selectors.
Example:
selector := "app=nginx,env=prod,tier=frontend"
labels := collections.SelectorToMap(selector)
// Result: {"app": "nginx", "env": "prod", "tier": "frontend"}
func SortedMap ¶ added in v1.22.0
SortedMap converts a map to a sorted key=value string representation. Keys are sorted alphabetically for consistent output.
Example:
labels := map[string]string{"tier": "web", "app": "nginx"}
result := collections.SortedMap(labels)
// Result: "app=nginx,tier=web"
func SplitAllInSlice ¶
SplitAllInSlice splits each element and returns the part at the specified index.
Example:
emails := []string{"john@example.com", "jane@test.org"}
domains := collections.SplitAllInSlice(emails, "@", 1)
// Result: ["example.com", "test.org"]
func StructToIni ¶
func StructToIni(s interface{}) string
StructToIni takes an object and serializes it's fields in INI format
func StructToJSON ¶ added in v1.8.0
StructToJSON takes an object and returns its json form
func StructToMap ¶
func StructToMap(s interface{}) map[string]interface{}
StructToMap takes an object and returns all it's field in a map
func ToBase64Map ¶
ToBase64Map converts a map[string]interface{} to a map[string]string. []byte values are encoded as base64, other types use fmt.Sprintf.
Example:
data := map[string]interface{}{
"text": "hello",
"binary": []byte{0x48, 0x65, 0x6c, 0x6c, 0x6f},
}
encoded := collections.ToBase64Map(data)
// Result: {"text": "hello", "binary": "SGVsbG8="}
func ToByteMap ¶
ToByteMap converts a map[string]interface{} to a map[string][]byte. String values are converted to []byte, []byte values are kept as-is.
func ToGenericMap ¶
ToGenericMap converts a map[string]string to a map[string]interface{}. Useful when you need to pass string maps to functions expecting generic maps.
Example:
strMap := map[string]string{"name": "John", "age": "30"}
generic := collections.ToGenericMap(strMap)
func ToJSONMap ¶ added in v1.37.0
ToJSONMap takes an input value of struct or map type and converts it to a map[string]any representation using JSON encoding and decoding.
func ToString ¶
func ToString(i interface{}) string
ToString converts various types to their string representation. Handles slices by joining elements with commas, fmt.Stringer types, strings, booleans, and falls back to fmt.Sprintf for other types.
Example:
collections.ToString([]int{1, 2, 3}) // "1, 2, 3"
collections.ToString(true) // "true"
collections.ToString(nil) // ""
func ToStringMap ¶
ToStringMap converts a map[string]interface{} to a map[string]string. Each value is converted using fmt.Sprintf("%v", value).
Example:
data := map[string]interface{}{"count": 42, "active": true}
strings := collections.ToStringMap(data)
// Result: {"count": "42", "active": "true"}
Types ¶
type MetricsOpts ¶ added in v1.32.0
type MetricsOpts[T comparable] struct { Labels map[string]any Labeller map[string]func(i T) string DurationBuckets []float64 Name string Disable bool }
MetricsOpts contains options for queue metrics
type Queue ¶ added in v1.32.0
type Queue[T comparable] struct { Comparator utils.Comparator[T] Equals func(a, b T) bool Dedupe bool // contains filtered or unexported fields }
Queue holds elements in an array-list Queue is a thread-safe priority queue implementation. Elements are ordered by a comparator function and can optionally be deduplicated using an equality function.
Example:
queue, _ := collections.NewQueue(collections.QueueOpts[int]{
Comparator: func(a, b int) int { return a - b }, // Min heap
Dedupe: true,
Equals: func(a, b int) bool { return a == b },
})
queue.Enqueue(5)
queue.Enqueue(1)
item, _ := queue.Dequeue() // Returns 1
func NewQueue ¶ added in v1.33.0
func NewQueue[T comparable](opts QueueOpts[T]) (*Queue[T], error)
NewQueue creates a new priority queue with the specified options. Returns an error if Dedupe is true but no Equals function is provided.
Example:
// Create a min-heap priority queue for tasks
queue, err := collections.NewQueue(collections.QueueOpts[Task]{
Comparator: func(a, b Task) int {
return a.Priority - b.Priority // Lower priority first
},
})
func (*Queue[T]) Clear ¶ added in v1.32.0
func (queue *Queue[T]) Clear()
Clear removes all elements from the queue.
func (*Queue[T]) Dequeue ¶ added in v1.32.0
Dequeue removes first element of the queue and returns it, or nil if queue is empty. Second return parameter is true, unless the queue was empty and there was nothing to dequeue.
func (*Queue[T]) Empty ¶ added in v1.32.0
Empty returns true if queue does not contain any elements.
func (*Queue[T]) Enqueue ¶ added in v1.32.0
func (queue *Queue[T]) Enqueue(value T)
Enqueue adds a value to the end of the queue
func (*Queue[T]) EnqueueWithDelay ¶ added in v1.35.0
Enqueue adds a value to the end of the queue
func (*Queue[T]) Peek ¶ added in v1.32.0
Peek returns top element on the queue without removing it, or nil if queue is empty. Second return parameter is true, unless the queue was empty and there was nothing to peek.
type QueueOpts ¶ added in v1.32.0
type QueueOpts[T comparable] struct { Comparator utils.Comparator[T] Dedupe bool Equals func(a, b T) bool Metrics MetricsOpts[T] }
QueueOpts configures a priority queue.