forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
58 lines (49 loc) · 1.26 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
package gobot
import (
"math"
"math/rand"
"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
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.
go f()
}
}()
}
// After triggers the passed function after `t` duration.
func After(t time.Duration, f func()) {
time.AfterFunc(t, f)
}
func Publish(e *Event, val interface{}) {
e.Write(val)
}
func On(e *Event, f func(s interface{})) {
e.Callbacks = append(e.Callbacks, callback{f, false})
}
func Once(e *Event, f func(s interface{})) {
e.Callbacks = append(e.Callbacks, callback{f, true})
}
func Rand(max int) int {
return rand.New(rand.NewSource(time.Now().UTC().UnixNano())).Intn(max)
}
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
}
}