-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbook.go
More file actions
100 lines (82 loc) · 1.49 KB
/
book.go
File metadata and controls
100 lines (82 loc) · 1.49 KB
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
package main
import (
"fmt"
"time"
)
type Book struct {
Title string
Self *Link
History []Checkout
}
type Checkout struct {
Who string
Out time.Time
In time.Time
Review int
}
type Link struct {
HRef string
ID string
}
var lib []Book
func init() {
lib = append(lib, Book{
Title: "Book 1",
Self: &Link{
HRef: "amazon.com",
ID: "1",
},
})
}
func get(id string) (book *Book) {
for _, l := range lib {
if l.Self.ID == id {
book = &l
break
}
}
return
}
func getAll() []Book {
return lib
}
func add(b Book) {
lib = append(lib, b)
}
func checkout(b *Book, name string) error {
h := len(b.History)
if h != 0 {
lastCheckout := b.History[h-1]
if lastCheckout.In.IsZero() {
return fmt.Errorf("this book is currently checked out to: [%s]", lastCheckout.Who)
}
}
if len(name) == 0 {
return fmt.Errorf("a name must be provided for checkout")
}
b.History = append(b.History, Checkout{
Who: name,
Out: time.Now(),
})
return nil
}
func checkin(b *Book, review int) error {
h := len(b.History)
if h == 0 {
return fmt.Errorf("this book is not currently checked out")
}
if review < 1 || review > 5 {
return fmt.Errorf("a review between 1 and 5 must be provided")
}
lastCheckout := b.History[h-1]
if !lastCheckout.In.IsZero() {
return fmt.Errorf("this book is not currently checked out")
}
b.History[h-1] = Checkout{
Who: lastCheckout.Who,
Out: lastCheckout.Out,
In: time.Now(),
Review: review,
}
return nil
}