1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-26 13:48:49 +08:00

72 lines
1.7 KiB
Go
Raw Normal View History

2014-04-30 08:10:44 -07:00
package gobot
2013-11-23 09:12:57 -08:00
import (
2014-03-26 22:24:45 -07:00
"math"
2013-11-23 09:12:57 -08:00
"math/rand"
"reflect"
"time"
)
// Every triggers f every `t` time until the end of days.
func Every(t time.Duration, f func()) {
c := time.Tick(t)
// start a go routine to not bloc the function
2013-11-23 09:12:57 -08:00
go func() {
for {
// wait for the ticker to tell us to run
<-c
// run the passed function in another go routine
// so we don't slow down the loop.
2013-11-23 09:12:57 -08:00
go f()
}
}()
}
// After triggers the passed function after `t` duration.
func After(t time.Duration, f func()) {
time.AfterFunc(t, f)
2013-11-23 09:12:57 -08:00
}
2014-06-11 11:37:20 -07:00
func Publish(e *Event, val interface{}) {
e.Write(val)
2013-12-30 19:06:13 -08:00
}
2014-06-11 11:37:20 -07:00
func On(e *Event, f func(s interface{})) {
e.Callbacks = append(e.Callbacks, f)
2013-12-30 19:06:13 -08:00
}
2013-11-23 09:12:57 -08:00
func Rand(max int) int {
2014-06-12 14:38:03 -07:00
r := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))
return r.Intn(max)
2013-11-23 09:12:57 -08:00
}
2013-11-24 14:41:36 -08:00
func Call(thing interface{}, method string, params ...interface{}) []reflect.Value {
2013-11-23 09:12:57 -08:00
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
2013-11-24 14:41:36 -08:00
return reflect.ValueOf(thing).MethodByName(method).Call(in)
2013-11-23 09:12:57 -08:00
}
2013-11-23 10:36:08 -08:00
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)
}
2014-03-26 22:24:45 -07:00
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
}
}