Documentation
¶
Overview ¶
Package mapx provides helper functions for working with maps.
Index ¶
- func All[M ~map[K]V, K comparable, V any](m M, predicate func(K, V) bool) bool
- func Any[M ~map[K]V, K comparable, V any](m M, predicate func(K, V) bool) bool
- func Apply[M ~map[K]V, K comparable, V any](collection M, apply func(key K, value V))
- func Combine[M ~map[K]V, K comparable, V any](maps ...M) M
- func Contains[M ~map[K]V, K comparable, V any](collection M, keys ...K) bool
- func CountBy[M ~map[K]V, K comparable, V any, R comparable](collection M, classifier func(key K, value V) R) map[R]int
- func Filter[M ~map[K]V, K comparable, V any](collection M, predicate func(key K, value V) bool) M
- func Invert[M ~map[K]V, K comparable, V comparable](collection M) map[V]K
- func Keys[M ~map[K]V, K comparable, V any](collection M) []K
- func MapKeys[M ~map[K]V, K comparable, V any, R comparable](collection M, mapper func(key K) R) map[R]V
- func MapValues[M ~map[K]V, K comparable, V, W any](m M, mapper func(V) W) map[K]W
- func Merge[M ~map[K]V, K comparable, V any](left, right M, resolver func(key K, left, right V) V) M
- func Partition[M ~map[K]V, K comparable, V any](collection M, predicate func(key K, value V) bool) (M, M)
- func SortedKeys[M ~map[K]V, K cmp.Ordered, V any](m M) []K
- func SortedKeysByFunc[M ~map[K]V, K comparable, V any](m M, cmpFn func(a, b K) int) []K
- func ToSlice[M ~map[K]V, K comparable, V any, R any](collection M, mapper func(key K, value V) R) []R
- func UniqueValues[M ~map[K]V, K comparable, V comparable](collection M) []V
- func ValueOr[M ~map[K]V, K comparable, V any](collection M, key K, fallback V) V
- func Values[M ~map[K]V, K comparable, V any](collection M) []V
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func All ¶ added in v1.2.4
func All[M ~map[K]V, K comparable, V any](m M, predicate func(K, V) bool) bool
All returns true if every entry in the map satisfies the predicate. Returns true for an empty map.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
inventory := map[string]int{"apples": 5, "bananas": 3, "cherries": 12}
allInStock := mapx.All(inventory, func(_ string, qty int) bool { return qty > 0 })
allAboveTen := mapx.All(inventory, func(_ string, qty int) bool { return qty > 10 })
fmt.Println(allInStock, allAboveTen)
}
Output: true false
func Any ¶ added in v1.2.4
func Any[M ~map[K]V, K comparable, V any](m M, predicate func(K, V) bool) bool
Any returns true if any entry in the map satisfies the predicate. Returns false for an empty map.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
inventory := map[string]int{"apples": 5, "bananas": 0, "cherries": 12}
hasEmpty := mapx.Any(inventory, func(_ string, qty int) bool { return qty == 0 })
hasHuge := mapx.Any(inventory, func(_ string, qty int) bool { return qty > 100 })
fmt.Println(hasEmpty, hasHuge)
}
Output: true false
func Apply ¶
func Apply[M ~map[K]V, K comparable, V any](collection M, apply func(key K, value V))
Apply calls the provided function on each key-value pair in the map for side effects. No new map is returned.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
var result string
mapx.Apply(numMap, func(key int, value string) {
if key == 256 {
result = value
}
})
fmt.Println(result)
}
Output: five
func Combine ¶
func Combine[M ~map[K]V, K comparable, V any](maps ...M) M
Combine merges all provided maps into a single new map. If the same key appears in multiple maps, the resulting value is non-deterministic. Use Merge for explicit control over conflict resolution.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var (
numMap1 = map[int]string{0: "zero", 8: "one", 2: "two"}
numMap2 = map[int]string{3: "three", 12: "four", 256: "five"}
)
result := mapx.Combine(numMap1, numMap2)
fmt.Println(result)
}
Output: map[0:zero 2:two 3:three 8:one 12:four 256:five]
func Contains ¶
func Contains[M ~map[K]V, K comparable, V any](collection M, keys ...K) bool
Contains returns true if the map contains all of the specified keys, false otherwise.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
result1 := mapx.Contains(numMap, 0)
result2 := mapx.Contains(numMap, 1)
result3 := mapx.Contains(numMap, 2, 8, 256)
fmt.Println(result1, result2, result3)
}
Output: true false true
func CountBy ¶ added in v1.1.0
func CountBy[M ~map[K]V, K comparable, V any, R comparable](collection M, classifier func(key K, value V) R) map[R]int
CountBy returns a map of counts grouped by the result of the classifier function. The classifier is called for each entry; the returned map tracks how many entries produced each key.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
inventory := map[string]int{
"apple": 5,
"banana": 12,
"cherry": 3,
"date": 8,
"elderberry": 1,
}
result := mapx.CountBy(inventory, func(_ string, qty int) string {
if qty < 5 {
return "low"
}
return "ok"
})
fmt.Println(result)
}
Output: map[low:2 ok:3]
func Filter ¶
func Filter[M ~map[K]V, K comparable, V any](collection M, predicate func(key K, value V) bool) M
Filter returns a new map containing only the entries for which the predicate returns true.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
result := mapx.Filter(numMap, func(key int, _ string) bool {
return key%2 != 0
})
fmt.Println(result)
}
Output: map[3:three]
func Invert ¶
func Invert[M ~map[K]V, K comparable, V comparable](collection M) map[V]K
Invert returns a new map with keys and values swapped. If multiple keys map to the same value, the resulting key in the inverted map is non-deterministic.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
inverted := mapx.Invert(numMap)
fmt.Println(inverted)
}
Output: map[five:256 four:12 one:8 three:3 two:2 zero:0]
func Keys ¶
func Keys[M ~map[K]V, K comparable, V any](collection M) []K
Keys returns a slice of all keys in the map. The order of the result is not guaranteed.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
keys := mapx.Keys(numMap)
slices.Sort(keys)
fmt.Println(keys)
}
Output: [0 2 3 8 12 256]
func MapKeys ¶ added in v1.1.0
func MapKeys[M ~map[K]V, K comparable, V any, R comparable](collection M, mapper func(key K) R) map[R]V
MapKeys returns a new map with each key transformed by the mapper function. Values are preserved unchanged. If the mapper produces duplicate keys, the resulting value is non-deterministic. The original map is not modified.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
scores := map[string]int{
"alice": 90,
"bob": 75,
"carol": 88,
}
result := mapx.MapKeys(scores, func(key string) string {
return "user_" + key
})
fmt.Println(result)
}
Output: map[user_alice:90 user_bob:75 user_carol:88]
func MapValues ¶ added in v1.2.4
func MapValues[M ~map[K]V, K comparable, V, W any](m M, mapper func(V) W) map[K]W
MapValues returns a new map with each value transformed by the mapper function. Keys are preserved unchanged. The original map is not modified.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
scores := map[string]int{
"alice": 90,
"bob": 75,
"carol": 88,
}
grades := mapx.MapValues(scores, func(score int) string {
if score >= 90 {
return "A"
}
return "B"
})
fmt.Println(grades["alice"])
fmt.Println(grades["bob"])
fmt.Println(grades["carol"])
}
Output: A B B
func Merge ¶ added in v1.2.0
func Merge[M ~map[K]V, K comparable, V any](left, right M, resolver func(key K, left, right V) V) M
Merge combines two maps into a single new map, using the resolver function to determine the value when a key exists in both maps. Keys that appear in only one map are included as-is. Unlike Combine, which uses non-deterministic last-write-wins, Merge gives the caller explicit control over conflict resolution.
Example (KeepLeft) ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
defaults := map[string]int{"timeout": 30, "retries": 3, "workers": 5}
overrides := map[string]int{"timeout": 60, "debug": 1}
// caller-supplied values win; defaults fill in the rest
result := mapx.Merge(overrides, defaults, func(_ string, left, _ int) int {
return left
})
fmt.Println(result["timeout"]) // from overrides
fmt.Println(result["retries"]) // from defaults, no conflict
fmt.Println(result["debug"]) // from overrides, no conflict
}
Output: 60 3 1
Example (Sum) ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
pageViews := map[string]int{"home": 100, "about": 40}
moreViews := map[string]int{"home": 50, "contact": 20}
result := mapx.Merge(pageViews, moreViews, func(_ string, left, right int) int {
return left + right
})
fmt.Println(result["home"]) // combined
fmt.Println(result["about"]) // no conflict
fmt.Println(result["contact"]) // no conflict
}
Output: 150 40 20
func Partition ¶ added in v1.1.0
func Partition[M ~map[K]V, K comparable, V any](collection M, predicate func(key K, value V) bool) (M, M)
Partition splits a map into two maps based on a predicate. Entries for which the predicate returns true are placed in the first map; the remaining entries are placed in the second.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
2: "two",
3: "three",
8: "one",
12: "four",
256: "five",
}
even, odd := mapx.Partition(numMap, func(key int, _ string) bool {
return key%2 == 0
})
fmt.Println(even)
fmt.Println(odd)
}
Output: map[0:zero 2:two 8:one 12:four 256:five] map[3:three]
func SortedKeys ¶ added in v1.2.4
SortedKeys returns the keys of the map sorted in ascending order. The key type must satisfy cmp.Ordered. Use SortedKeysByFunc for custom ordering.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
scores := map[int]string{3: "three", 1: "one", 2: "two"}
keys := mapx.SortedKeys(scores)
fmt.Println(keys)
}
Output: [1 2 3]
func SortedKeysByFunc ¶ added in v1.2.4
func SortedKeysByFunc[M ~map[K]V, K comparable, V any](m M, cmpFn func(a, b K) int) []K
SortedKeysByFunc returns the keys of the map sorted using the provided comparison function. cmpFn should return a negative number when a < b, zero when a == b, and a positive number when a > b, consistent with the cmp.Compare convention.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
scores := map[string]int{"alice": 90, "bob": 75, "carol": 88}
keys := mapx.SortedKeysByFunc(scores, func(a, b string) int {
return scores[b] - scores[a] // descending by score
})
fmt.Println(keys)
}
Output: [alice carol bob]
func ToSlice ¶
func ToSlice[M ~map[K]V, K comparable, V any, R any](collection M, mapper func(key K, value V) R) []R
ToSlice converts a map into a slice by applying the mapper function to each key-value pair. The order of the result is not guaranteed.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
values := mapx.ToSlice(numMap, func(key int, value string) string {
return fmt.Sprintf("%d-%s", key, value)
})
slices.Sort(values)
fmt.Println(values)
}
Output: [0-zero 12-four 2-two 256-five 3-three 8-one]
func UniqueValues ¶
func UniqueValues[M ~map[K]V, K comparable, V comparable](collection M) []V
UniqueValues returns a slice of the map's values with duplicates removed. The order of the result is not guaranteed.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var dupMap = map[int]string{
0: "zero",
8: "zero",
2: "two",
3: "five",
12: "five",
256: "five",
8192: "five",
}
values := mapx.UniqueValues(dupMap)
slices.Sort(values)
fmt.Println(values)
}
Output: [five two zero]
func ValueOr ¶ added in v0.1.0
func ValueOr[M ~map[K]V, K comparable, V any](collection M, key K, fallback V) V
ValueOr returns the value for the given key, or fallback if the key is not present.
Example ¶
package main
import (
"fmt"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
result1 := mapx.ValueOr(numMap, 0, "nothing")
result2 := mapx.ValueOr(numMap, 1, "nothing")
fmt.Println(result1, result2)
}
Output: zero nothing
func Values ¶
func Values[M ~map[K]V, K comparable, V any](collection M) []V
Values returns a slice of all values in the map. The order of the result is not guaranteed.
Example ¶
package main
import (
"fmt"
"slices"
"github.com/SharkByteSoftware/go-snk/mapx"
)
func main() {
var numMap = map[int]string{
0: "zero",
8: "one",
2: "two",
3: "three",
12: "four",
256: "five",
}
values := mapx.Values(numMap)
slices.Sort(values)
fmt.Println(values)
}
Output: [five four one three two zero]
Types ¶
This section is empty.