-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (79 loc) · 1.56 KB
/
main.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
package main
import (
"fmt"
"syscall"
"time"
"unicode"
"golang.org/x/crypto/ssh/terminal"
)
type stopwatch struct {
elapsed time.Duration
lastElapsed time.Duration
start time.Time
lastStart time.Time
isRunning bool
}
func (s *stopwatch) Start() {
if !s.isRunning {
s.start = time.Now()
s.lastStart = s.start
s.isRunning = true
}
}
func (s *stopwatch) Stop() {
if s.isRunning {
s.lastElapsed = time.Since(s.lastStart)
s.elapsed += time.Since(s.start)
s.isRunning = false
}
}
func (s *stopwatch) Flip() {
if s.isRunning {
s.Stop()
} else {
s.Start()
}
}
func (s *stopwatch) Elapsed() time.Duration {
if s.isRunning {
s.elapsed += time.Since(s.start)
s.start = time.Now()
}
return s.elapsed
}
func newStopwatch(start bool) stopwatch {
var sw stopwatch
if start {
sw.Start()
}
return sw
}
// Format Duration
func fd(d time.Duration) string {
var ns string
var period bool
for _, r := range d.String() {
if (period && unicode.IsDigit(r)) || r == '.' {
period = true
continue
}
ns += string(r)
}
return ns
}
func main() {
working, distracted := newStopwatch(true), newStopwatch(false)
fmt.Println("press enter to flip, ctrl+c to exit")
fmt.Println("Type: Current Elapsed (Last Elapsed)")
go func() {
for {
terminal.ReadPassword(int(syscall.Stdin))
working.Flip()
distracted.Flip()
}
}()
for {
fmt.Printf("\rWorking: %s (%s)\t\tDistracted %s (%s)\t\t", fd(working.Elapsed()), fd(working.lastElapsed), fd(distracted.Elapsed()), fd(distracted.lastElapsed))
time.Sleep(time.Millisecond * 50)
}
}