-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
61 lines (54 loc) · 1.34 KB
/
timer.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
package cooklang
import (
"encoding/json"
"fmt"
"strings"
)
// Timer represents a timer used in a recipe
type Timer struct {
Name string `json:"name"`
Quantity
raw string
stepPos int
}
// NewTimer creates a new Timer from a timer definition
func NewTimer(source string) *Timer {
t := Timer{raw: source}
ns := strings.IndexRune(source, '~') + 1
qs := strings.IndexRune(source, '{')
t.Name = source[ns:qs]
var err error
if t.Quantity, err = strictParseQuantity(source[qs : len(source)-2]); err != nil {
// TODO: how to handle a parse error here?
// preferably the lexer shouldn't emit as a timer so
// maybe unnecessary to do much
fmt.Printf("invalid quantity for timer %q: %v\n", source, err)
}
return &t
}
// String implements Stringer for Timer
func (t Timer) String() string {
return t.raw
}
// DirectionItem creates a new direction item from the Timer
func (t Timer) DirectionItem() DirectionItem {
return DirectionItem{
Type: "timer",
Name: t.Name,
Quantity: t.S,
Units: t.Units,
}
}
// MarshalJSON implements json.Marshaler for Timer
func (t Timer) MarshalJSON() ([]byte, error) {
tt := struct {
Name string `json:"name,omitempty"`
Quantity string `json:"quantity"`
Units string `json:"units"`
}{
Name: t.Name,
Quantity: t.Quantity.S,
Units: t.Units,
}
return json.Marshal(tt)
}