-
Notifications
You must be signed in to change notification settings - Fork 0
/
chime.go
115 lines (91 loc) · 1.8 KB
/
chime.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package chimer
import (
"time"
)
type Chime int64
func (w Chime) String() string {
switch w {
case Hour:
return "Hour"
case QuarterPast:
return "QuarterPast"
case HalfPast:
return "HalfPast"
case QuarterTo:
return "QuarterTo"
case None:
return "None"
default:
panic("unknown value")
}
}
const (
None Chime = iota
Hour
QuarterPast
HalfPast
QuarterTo
)
func secondsFromMidnight(t time.Time) int {
hour := t.Hour()
minute := t.Minute()
seconds := t.Second()
return (hour*60+minute)*60 + seconds
}
func GetChime(t time.Time, tolerance time.Duration) (int, Chime) {
t = t.Local()
hour := t.Hour()
seconds := secondsFromMidnight(t)
if hour > 12 {
hour -= 12
}
if hourItIs, increment := isHour(seconds, int(tolerance.Seconds())); hourItIs {
return hour + increment, Hour
}
if isHalfHour(seconds, int(tolerance.Seconds())) {
return hour, HalfPast
}
if isQuarterHour(seconds, int(tolerance.Seconds())) {
if t.Minute() > 40 {
return hour, QuarterTo
}
return hour, QuarterPast
}
return hour, None
}
const quarterlySeconds = 15 * 60
const halfHourlySeconds = 2 * quarterlySeconds
const hourSeconds = 4 * quarterlySeconds
func isHour(s, t int) (bool, int) {
return isMultipleOfWithTolerance(hourSeconds, s, t)
}
func isQuarterHour(s, t int) bool {
ret, _ := isMultipleOfWithTolerance(quarterlySeconds, s, t)
return ret
}
func isHalfHour(s, t int) bool {
ret, _ := isMultipleOfWithTolerance(halfHourlySeconds, s, t)
return ret
}
func isMultipleOfWithTolerance(m, s, t int) (bool, int) {
r := s % m
// if we are on the dot
if r == 0 {
return true, 0
}
// if there is no tolerance
if t == 0 {
return false, 0
}
// a negative numbers for tolerance?!
if t < 0 {
t = -t
}
if r >= (m - t) {
return true, 1
}
if r <= t {
return true, 0
}
return false, 0
}