-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
67 lines (51 loc) · 1.21 KB
/
map.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
package lo
// Keys creates an array of the map keys.
func Keys[K comparable, V any](in map[K]V) []K {
result := make([]K, 0, len(in))
for k, _ := range in {
result = append(result, k)
}
return result
}
// Values creates an array of the map values.
func Values[K comparable, V any](in map[K]V) []V {
result := make([]V, 0, len(in))
for _, v := range in {
result = append(result, v)
}
return result
}
// Entry defines a key/value pairs.
type Entry[K comparable, V any] struct {
Key K
Value V
}
// Entries transforms a map into array of key/value pairs.
func Entries[K comparable, V any](in map[K]V) []Entry[K, V] {
entries := make([]Entry[K, V], 0, len(in))
for k, v := range in {
entries = append(entries, Entry[K, V]{
Key: k,
Value: v,
})
}
return entries
}
// FromEntries transforms an array of key/value pairs into a map.
func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V {
out := map[K]V{}
for _, v := range entries {
out[v.Key] = v.Value
}
return out
}
// Assign merges multiple maps from left to right.
func Assign[K comparable, V any](maps ...map[K]V) map[K]V {
out := map[K]V{}
for _, m := range maps {
for k, v := range m {
out[k] = v
}
}
return out
}