hybridgroup.gobot/utils.go

66 lines
1.5 KiB
Go
Raw Normal View History

2014-04-30 23:10:44 +08:00
package gobot
2013-11-24 01:12:57 +08:00
import (
"crypto/rand"
2014-03-27 13:24:45 +08:00
"math"
"math/big"
2013-11-24 01:12:57 +08:00
"time"
)
// Every triggers f every `t` time until the end of days.
func Every(t time.Duration, f func()) {
c := time.Tick(t)
2014-10-16 01:57:07 +08:00
2013-11-24 01:12:57 +08:00
go func() {
for {
<-c
2013-11-24 01: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-24 01:12:57 +08:00
}
2014-10-16 01:57:07 +08:00
// Publish emits an event by writting value
2014-06-12 02:37:20 +08:00
func Publish(e *Event, val interface{}) {
e.Write(val)
2013-12-31 11:06:13 +08:00
}
2014-10-16 01:57:07 +08:00
// On adds `f` to callbacks that are executed on specified event
2014-06-12 02:37:20 +08:00
func On(e *Event, f func(s interface{})) {
2014-07-14 11:27:38 +08:00
e.Callbacks = append(e.Callbacks, callback{f, false})
}
2014-10-16 01:57:07 +08:00
// Once adds `f` to callbacks that are executed on specified event
// and sets flag to be called only once
2014-07-14 11:27:38 +08:00
func Once(e *Event, f func(s interface{})) {
e.Callbacks = append(e.Callbacks, callback{f, true})
2013-12-31 11:06:13 +08:00
}
2014-10-16 01:57:07 +08:00
// Rand generates random int lower than max
2013-11-24 01:12:57 +08:00
func Rand(max int) int {
i, _ := rand.Int(rand.Reader, big.NewInt(int64(max)))
return int(i.Int64())
2013-11-24 01:12:57 +08:00
}
2014-10-16 01:57:07 +08:00
// FromScale creates a scale using min and max values
// to be used in combination with ToScale
2014-03-27 13:24:45 +08:00
func FromScale(input, min, max float64) float64 {
return (input - math.Min(min, max)) / (math.Max(min, max) - math.Min(min, max))
}
2014-10-16 01:57:07 +08:00
// ToScale is used with FromScale to return input converted to new scale
2014-03-27 13:24:45 +08:00
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
}
}