-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyvalue.go
44 lines (34 loc) · 922 Bytes
/
keyvalue.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
package do
// KeyValueBy slice to map, key value specified by iteratee
func KeyValueBy[K comparable, E, V any](collection []E, iteratee func(item E) (K, V)) map[K]V {
result := make(map[K]V, len(collection))
for i := range collection {
k, r := iteratee(collection[i])
result[k] = r
}
return result
}
// KeyBy slice to map, key specified by iteratee, value is slice element
func KeyBy[K comparable, E any](collection []E, iteratee func(item E) K) map[K]E {
return KeyValueBy(collection, func(item E) (K, E) {
return iteratee(item), item
})
}
func Keys[K comparable, E any](collection map[K]E) []K {
result := make([]K, len(collection))
var i int
for k := range collection {
result[i] = k
i++
}
return result
}
func Values[K comparable, E any](collection map[K]E) []E {
result := make([]E, len(collection))
var i int
for _, v := range collection {
result[i] = v
i++
}
return result
}