forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
84 lines (73 loc) · 1.58 KB
/
utils.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
package gobot
import (
"math"
"math/rand"
"reflect"
"time"
)
func Every(t string, f func()) {
dur := parseDuration(t)
go func() {
for {
time.Sleep(dur)
go f()
}
}()
}
func After(t string, f func()) {
dur := parseDuration(t)
go func() {
time.Sleep(dur)
f()
}()
}
func Publish(c chan interface{}, val interface{}) {
select {
case c <- val:
default:
}
}
func On(c chan interface{}, f func(s interface{})) {
go func() {
for s := range c {
f(s)
}
}()
}
func Rand(max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max)
}
func Call(thing interface{}, method string, params ...interface{}) []reflect.Value {
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
return reflect.ValueOf(thing).MethodByName(method).Call(in)
}
func FieldByName(thing interface{}, field string) reflect.Value {
return reflect.ValueOf(thing).FieldByName(field)
}
func FieldByNamePtr(thing interface{}, field string) reflect.Value {
return reflect.ValueOf(thing).Elem().FieldByName(field)
}
func FromScale(input, min, max float64) float64 {
return (input - math.Min(min, max)) / (math.Max(min, max) - math.Min(min, max))
}
func ToScale(input, min, max float64) float64 {
i := input*(math.Max(min, max)-math.Min(min, max)) + math.Min(min, max)
if i < math.Min(min, max) {
return math.Min(min, max)
} else if i > math.Max(min, max) {
return math.Max(min, max)
} else {
return i
}
}
func parseDuration(t string) time.Duration {
dur, err := time.ParseDuration(t)
if err != nil {
panic(err)
}
return dur
}