-
Notifications
You must be signed in to change notification settings - Fork 0
/
maps.go
112 lines (97 loc) · 2.52 KB
/
maps.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Package maps provides handy functional programming -style
// functions that operate on map data types.
package maps
import (
"golang.org/x/exp/constraints"
)
// HasKey returns a function that tests if a key exists in the map.
func HasKey[K comparable, V any](pairs map[K]V) func(k K) bool {
return func(k K) bool { _, ok := pairs[k]; return ok }
}
// Key returns the key of a map key/value pair.
func Key[K comparable, V any](key K, value V) K {
return key
}
// Value returns the value of a map key/value pair.
func Value[K any, V any](key K, value V) V {
return value
}
// Keys returns the keys of a map.
func Keys[K comparable, V any](pairs map[K]V) []K {
keys := make([]K, 0, len(pairs))
for k := range pairs {
keys = append(keys, k)
}
return keys
}
// Values returns the values of a map.
func Values[K comparable, V any](pairs map[K]V) []V {
values := make([]V, 0, len(pairs))
for _, v := range pairs {
values = append(values, v)
}
return values
}
// ValueLen returns the length of the slice value of a map.
func ValueLen[K any, T any](key K, value []T) int {
return len(value)
}
// Map maps the (k,v) pairs to a slice of values.
func Map[K comparable, V any, T any](pairs map[K]V, f func(K, V) T) []T {
result := []T{}
for k, v := range pairs {
result = append(result, f(k, v))
}
return result
}
// Number has the "+" operator.
type Number interface {
constraints.Integer | constraints.Unsigned | constraints.Float | constraints.Complex
}
// Swap swaps the keys and values and returns a new map.
func Swap[K comparable, V comparable](pairs map[K]V) map[V]K {
ret := map[V]K{}
for k, v := range pairs {
ret[v] = k
}
return ret
}
// SumKeys sums up the keys in a map.
func SumKeys[K Number, V any](pairs map[K]V) (ret K) {
for k := range pairs {
ret += k
}
return ret
}
// SumValues sums up the values in a map.
func SumValues[K comparable, V Number](pairs map[K]V) (ret V) {
for _, v := range pairs {
ret += v
}
return ret
}
// ProductKeys multiples the keys in a map together.
func ProductKeys[K Number, V any](pairs map[K]V) (ret K) {
ret = K(1)
for k := range pairs {
ret *= k
}
return ret
}
// ProductValues multiples the values in a map together.
func ProductValues[K comparable, V Number](pairs map[K]V) (ret V) {
ret = V(1)
for _, v := range pairs {
ret *= v
}
return ret
}
// ShallowCopy makes a shallow copy (top key/value pairs only) of
// the given map.
func ShallowCopy[K comparable, V any](pairs map[K]V) map[K]V {
ret := map[K]V{}
for k, v := range pairs {
ret[k] = v
}
return ret
}