Documentation
¶
Overview ¶
Package maps provides generic utility functions to work with Go maps. It offers a functional approach to common map operations like filtering, mapping, reducing, and comparing maps.
Index ¶
- func Equals[K comparable, V any](m1, m2 map[K]V, eq func(V, V) bool) bool
- func Filter[K comparable, V any](m map[K]V, p func(K, V) bool) map[K]V
- func FilterInPlace[K comparable, V any](m map[K]V, p func(K, V) bool) map[K]V
- func FilterMap[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1, p func(K1, V1) fp.Option[tuples.Tuple2[K2, V2]]) map[K2]V2
- func FilterMapTuple[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1, p func(K1, V1) (K2, V2, bool)) map[K2]V2
- func Fold[K comparable, V any, R any](m map[K]V, p func(R, K, V) R, initial R) R
- func Keys[K comparable, V any](m map[K]V) []K
- func Map[K1 comparable, V1 any, K2 comparable, V2 any](m map[K1]V1, p func(K1, V1) (K2, V2)) map[K2]V2
- func Reduce[K comparable, V any, R any](m map[K]V, p func(R, K, V) R) R
- func SeqKeys[K comparable, V any](m map[K]V) iter.Seq[K]
- func SeqValues[K comparable, V any](m map[K]V) iter.Seq[V]
- func Slice[K comparable, V, R any](m map[K]V, p func(K, V) R) slices.Slice[R]
- func Values[K comparable, V any](m map[K]V) []V
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Equals ¶
func Equals[K comparable, V any](m1, m2 map[K]V, eq func(V, V) bool) bool
Equals compares two maps and returns whether they are equal in values. Two maps are considered equal if: - They have the same length - They contain the same keys - For each key, the values in both maps satisfy the equality function
Maps are compared using the provided equality function for values. This allows for deep equality checks on complex value types.
Example ¶
ExampleEquals demonstrates comparing two maps for equality.
// Create two maps
map1 := map[string]int{"a": 1, "b": 2, "c": 3}
map2 := map[string]int{"a": 1, "b": 2, "c": 3}
map3 := map[string]int{"a": 1, "b": 2, "c": 4}
// Compare using equality function
equal1 := Equals(map1, map2, func(x, y int) bool { return x == y })
equal2 := Equals(map1, map3, func(x, y int) bool { return x == y })
fmt.Printf("map1 == map2: %t\n", equal1)
fmt.Printf("map1 == map3: %t\n", equal2)
Output: map1 == map2: true map1 == map3: false
func Filter ¶
func Filter[K comparable, V any]( m map[K]V, p func(K, V) bool, ) map[K]V
Filter creates a new map containing only the key-value pairs that satisfy the predicate. The predicate function takes a key and value and returns a boolean indicating whether to include the entry in the result.
Unlike FilterInPlace, this function creates a new map and does not modify the input map.
Example ¶
ExampleFilter demonstrates filtering a map by key-value pairs.
// Create a map of products to prices
prices := map[string]int{
"apple": 100,
"banana": 50,
"cherry": 200,
"date": 75,
}
// Keep only items that cost more than 75
expensive := Filter(prices, func(product string, price int) bool {
return price > 75
})
fmt.Printf("Expensive items count: %d\n", len(expensive))
Output: Expensive items count: 2
func FilterInPlace ¶
func FilterInPlace[K comparable, V any]( m map[K]V, p func(K, V) bool, ) map[K]V
FilterInPlace modifies the given map by removing entries that do not satisfy the predicate. The predicate function takes a key and value and returns a boolean indicating whether to keep the entry in the map.
This function directly modifies the input map for better performance when creating a new map is not necessary. It returns the modified map for convenience in chaining operations.
func FilterMap ¶
func FilterMap[K1 comparable, V1 any, K2 comparable, V2 any]( m map[K1]V1, p func(K1, V1) fp.Option[tuples.Tuple2[K2, V2]], ) map[K2]V2
FilterMap both filters and maps a map into a new map, potentially with different key and value types. The predicate function should return an fp.Option monad containing a tuple of the new key and value: - fp.Some to include the entry in the result (with transformed key and value) - fp.None to exclude the entry from the result
This provides a powerful way to simultaneously transform and filter map entries while leveraging the Option monad for expressing presence/absence.
Example ¶
ExampleFilterMap demonstrates filtering and transforming in a single operation.
// Create a map of names to ages
ages := map[string]int{
"Alice": 25,
"Bob": 17,
"Carol": 30,
"Dave": 16,
}
// Keep only adults and transform to ID format
adults := FilterMap(ages, func(name string, age int) fp.Option[tuples.Tuple2[string, string]] {
if age >= 18 {
id := fmt.Sprintf("ID_%s_%d", name, age)
return fp.Some(tuples.Tuple2[string, string]{V1: name, V2: id})
}
return fp.None[tuples.Tuple2[string, string]]()
})
fmt.Printf("Adult count: %d\n", len(adults))
Output: Adult count: 2
func FilterMapTuple ¶
func FilterMapTuple[K1 comparable, V1 any, K2 comparable, V2 any]( m map[K1]V1, p func(K1, V1) (K2, V2, bool), ) map[K2]V2
FilterMapTuple both filters and maps the given map into a new map, potentially with different key and value types. The predicate function returns three values: - The new key (K2) - The new value (V2) - A boolean indicating whether to include this entry in the result
This function is an alternative to FilterMap that uses Go's native boolean return instead of the Option monad for expressing presence/absence.
Example ¶
ExampleFilterMapTuple demonstrates filtering and transforming using tuple returns.
// Create a map of scores
scores := map[string]int{
"Alice": 85,
"Bob": 70,
"Carol": 95,
"Dave": 60,
}
// Keep high scores and convert to grade format
grades := FilterMapTuple(scores, func(name string, score int) (string, string, bool) {
if score >= 80 {
var grade string
if score >= 90 {
grade = "A"
} else {
grade = "B"
}
return name, grade, true
}
return "", "", false
})
fmt.Printf("High performers: %d\n", len(grades))
fmt.Printf("Alice's grade: %s\n", grades["Alice"])
Output: High performers: 2 Alice's grade: B
func Fold ¶
func Fold[K comparable, V any, R any]( m map[K]V, p func(R, K, V) R, initial R, ) R
Fold compacts a map into a single value by iteratively applying a reduction function with an explicit initial value. The reduction function takes the accumulator, a key, and a value, and returns the updated accumulator.
Unlike Reduce, Fold takes an explicit initial value for the accumulator. This is useful when the zero value of the result type is not appropriate as the starting value.
Example ¶
ExampleFold demonstrates folding a map with an initial value.
// Create a map of item prices
prices := map[string]float64{
"apple": 1.20,
"banana": 0.80,
"cherry": 2.50,
}
// Calculate total with initial tax
totalWithTax := Fold(prices, func(acc float64, item string, price float64) float64 {
return acc + price*1.1 // Add 10% tax
}, 5.0) // Start with 5.0 base fee
fmt.Printf("Total with tax: %.2f\n", totalWithTax)
Output: Total with tax: 9.95
func Keys ¶ added in v0.8.2
func Keys[K comparable, V any](m map[K]V) []K
Keys extracts all keys from a map and returns them as a slice. The order of keys in the resulting slice is not guaranteed, as map iteration in Go is not deterministic.
This function uses Go's built-in maps.Keys iterator and collects the results into a standard slice for convenient manipulation.
Example ¶
ExampleKeys demonstrates extracting all keys from a map.
// Create a map of products to prices
prices := map[string]int{
"apple": 100,
"banana": 50,
"cherry": 200,
}
// Extract all product names
products := Keys(prices)
fmt.Printf("Product count: %d\n", len(products))
// Note: map iteration order is not guaranteed
func Map ¶
func Map[K1 comparable, V1 any, K2 comparable, V2 any]( m map[K1]V1, p func(K1, V1) (K2, V2), ) map[K2]V2
Map transforms a map into another map, with potentially different key and value types. The transformation is applied to each key-value pair by the provided function, which returns the new key and value for the resulting map.
This function preserves nil semantics: if the input map is nil, the output will also be nil. Otherwise, a new map is created with the transformed key-value pairs.
Example ¶
ExampleMap demonstrates transforming keys and values in a map.
// Create a map of numbers to their names
numbers := map[int]string{
1: "one",
2: "two",
3: "three",
}
// Transform to string keys and uppercase values
transformed := Map(numbers, func(key int, value string) (string, string) {
return fmt.Sprintf("num_%d", key), strings.ToUpper(value)
})
fmt.Println(transformed["num_1"])
Output: ONE
func Reduce ¶
func Reduce[K comparable, V any, R any]( m map[K]V, p func(R, K, V) R, ) R
Reduce compacts a map into a single value by iteratively applying a reduction function. The reduction function takes the accumulator, a key, and a value, and returns the updated accumulator.
The initial value for the accumulator is the zero value of type R. If you need a different initial value, use Fold instead.
Example ¶
ExampleReduce demonstrates reducing a map to a single value.
// Create a map of item quantities
inventory := map[string]int{
"apples": 10,
"bananas": 5,
"oranges": 8,
}
// Calculate total items (Reduce starts with zero value)
total := Reduce(inventory, func(acc int, key string, value int) int {
return acc + value
})
fmt.Printf("Total items: %d\n", total)
Output: Total items: 23
func SeqKeys ¶ added in v0.8.2
func SeqKeys[K comparable, V any](m map[K]V) iter.Seq[K]
SeqKeys returns an iterator sequence that yields all keys from a map. This function uses Go 1.23's iterator pattern and leverages the built-in maps.Keys function.
The iteration order is not guaranteed, as map iteration in Go is not deterministic. This is useful for streaming operations or when you want to process keys lazily.
Example ¶
ExampleSeqKeys demonstrates iterating over map keys using iterator pattern.
// Create a map of products to prices
prices := map[string]int{
"apple": 100,
"banana": 50,
"cherry": 200,
}
// Iterate over keys lazily
keyCount := 0
for range SeqKeys(prices) {
keyCount++
}
fmt.Printf("Key count: %d\n", keyCount)
Output: Key count: 3
func SeqValues ¶ added in v0.8.2
func SeqValues[K comparable, V any](m map[K]V) iter.Seq[V]
SeqValues returns an iterator sequence that yields all values from a map. This function uses Go 1.23's iterator pattern and leverages the built-in maps.Values function.
The iteration order is not guaranteed, as map iteration in Go is not deterministic. This is useful for streaming operations or when you want to process values lazily.
Example ¶
ExampleSeqValues demonstrates iterating over map values using iterator pattern.
// Create a map of products to prices
prices := map[string]int{
"apple": 100,
"banana": 50,
"cherry": 200,
}
// Calculate total using iterator
total := 0
for price := range SeqValues(prices) {
total += price
}
fmt.Printf("Total price: %d\n", total)
Output: Total price: 350
func Slice ¶
func Slice[K comparable, V, R any]( m map[K]V, p func(K, V) R, ) slices.Slice[R]
Slice converts a map into a slice by applying a transformation function to each key-value pair. The transformation function takes a key and value and returns an element for the resulting slice.
The order of elements in the resulting slice is not guaranteed, as map iteration in Go is not deterministic.
Example ¶
ExampleSlice demonstrates converting a map to a slice.
// Create a map of user data
users := map[int]string{
1: "Alice",
2: "Bob",
3: "Carol",
}
// Convert to slice of formatted strings
userList := Slice(users, func(id int, name string) string {
return fmt.Sprintf("ID:%d Name:%s", id, name)
})
fmt.Printf("Users count: %d\n", len(userList))
// Note: map iteration order is not guaranteed
func Values ¶ added in v0.8.2
func Values[K comparable, V any](m map[K]V) []V
Values extracts all values from a map and returns them as a slice. The order of values in the resulting slice is not guaranteed, as map iteration in Go is not deterministic.
This function uses Go's built-in maps.Values iterator and collects the results into a standard slice for convenient manipulation.
Example ¶
ExampleValues demonstrates extracting all values from a map.
// Create a map of products to prices
prices := map[string]int{
"apple": 100,
"banana": 50,
"cherry": 200,
}
// Extract all prices
allPrices := Values(prices)
fmt.Printf("Price count: %d\n", len(allPrices))
// Note: map iteration order is not guaranteed
Types ¶
This section is empty.