2020-05-28 00:06:29 +00:00
|
|
|
package parmap
|
2019-11-15 16:38:56 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2020-06-02 14:29:39 +00:00
|
|
|
// MapArr transforms map into slice of map values
|
2020-05-28 00:06:29 +00:00
|
|
|
func MapArr(in interface{}) interface{} {
|
2019-11-15 18:37:57 +00:00
|
|
|
rin := reflect.ValueOf(in)
|
|
|
|
rout := reflect.MakeSlice(reflect.SliceOf(rin.Type().Elem()), rin.Len(), rin.Len())
|
|
|
|
var i int
|
|
|
|
|
|
|
|
it := rin.MapRange()
|
|
|
|
for it.Next() {
|
|
|
|
rout.Index(i).Set(it.Value())
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return rout.Interface()
|
|
|
|
}
|
|
|
|
|
2020-06-02 14:29:39 +00:00
|
|
|
// KMapArr transforms map into slice of map keys
|
2020-05-28 00:06:29 +00:00
|
|
|
func KMapArr(in interface{}) interface{} {
|
2019-11-15 18:37:57 +00:00
|
|
|
rin := reflect.ValueOf(in)
|
2019-11-16 12:34:52 +00:00
|
|
|
rout := reflect.MakeSlice(reflect.SliceOf(rin.Type().Key()), rin.Len(), rin.Len())
|
2019-11-15 18:37:57 +00:00
|
|
|
var i int
|
|
|
|
|
|
|
|
it := rin.MapRange()
|
|
|
|
for it.Next() {
|
|
|
|
rout.Index(i).Set(it.Key())
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return rout.Interface()
|
|
|
|
}
|
|
|
|
|
2020-06-02 16:38:41 +00:00
|
|
|
// KVMapArr transforms map into slice of functions returning (key, val) pairs.
|
2020-06-02 14:29:39 +00:00
|
|
|
// map[A]B => []func()(A, B)
|
2020-05-28 00:06:29 +00:00
|
|
|
func KVMapArr(in interface{}) interface{} {
|
2019-11-16 12:34:52 +00:00
|
|
|
rin := reflect.ValueOf(in)
|
|
|
|
|
|
|
|
t := reflect.FuncOf([]reflect.Type{}, []reflect.Type{
|
|
|
|
rin.Type().Key(),
|
|
|
|
rin.Type().Elem(),
|
|
|
|
}, false)
|
|
|
|
|
|
|
|
rout := reflect.MakeSlice(reflect.SliceOf(t), rin.Len(), rin.Len())
|
|
|
|
var i int
|
|
|
|
|
|
|
|
it := rin.MapRange()
|
|
|
|
for it.Next() {
|
|
|
|
k := it.Key()
|
|
|
|
v := it.Value()
|
|
|
|
|
|
|
|
rout.Index(i).Set(reflect.MakeFunc(t, func(args []reflect.Value) (results []reflect.Value) {
|
|
|
|
return []reflect.Value{k, v}
|
|
|
|
}))
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
|
|
|
return rout.Interface()
|
|
|
|
}
|
|
|
|
|
2020-05-28 00:06:29 +00:00
|
|
|
func Par(concurrency int, arr interface{}, f interface{}) {
|
2019-11-15 16:38:56 +00:00
|
|
|
throttle := make(chan struct{}, concurrency)
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
|
|
|
varr := reflect.ValueOf(arr)
|
|
|
|
l := varr.Len()
|
|
|
|
|
|
|
|
rf := reflect.ValueOf(f)
|
|
|
|
|
|
|
|
wg.Add(l)
|
|
|
|
for i := 0; i < l; i++ {
|
|
|
|
throttle <- struct{}{}
|
|
|
|
|
2019-11-15 18:37:57 +00:00
|
|
|
go func(i int) {
|
2019-11-15 16:38:56 +00:00
|
|
|
defer wg.Done()
|
|
|
|
defer func() {
|
|
|
|
<-throttle
|
|
|
|
}()
|
|
|
|
rf.Call([]reflect.Value{varr.Index(i)})
|
2019-11-15 18:37:57 +00:00
|
|
|
}(i)
|
2019-11-15 16:38:56 +00:00
|
|
|
}
|
2019-11-15 18:37:57 +00:00
|
|
|
|
|
|
|
wg.Wait()
|
2019-11-15 16:38:56 +00:00
|
|
|
}
|