-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
59 lines (45 loc) · 1.17 KB
/
convert.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
package collfunc
// ToSlice initializes and returns a new slice
// from the given collection
func ToSlice[T any](collection any) []T {
var slice []T
iter := Iterate[T](collection)
for v, ok := iter(); ok; v, ok = iter() {
slice = append(slice, v)
}
return slice
}
// ToMap initializes and returns a new map
// from the given collection, a mapping function
// is called to map a value for every key
func ToMap[K comparable, V any](collection any, f func(K) V) map[K]V {
m := make(map[K]V)
iter := Iterate[K](collection)
for k, ok := iter(); ok; k, ok = iter() {
m[k] = f(k)
}
return m
}
// CreateMap initializes and returns a new map
// with keys from the keys collection and corresponding
// values from the values collection
func CreateMap[K comparable, V any](keys any, values any) map[K]V {
iter := Iterate[V](values)
return ToMap(keys, func(K) V {
v, _ := iter()
return v
})
}
// ToChan writes all given collection items to a newly
// created channel
func ToChan[T any](collection any) <-chan T {
ch := make(chan T)
iter := Iterate[T](collection)
go func() {
defer close(ch)
for v, ok := iter(); ok; v, ok = iter() {
ch <- v
}
}()
return ch
}