-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbill.go
125 lines (97 loc) · 2.1 KB
/
bill.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
116
117
118
119
120
121
122
123
124
125
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type bill struct {
name string
items map[string]float64
tip float64
}
func newBill(name string) bill {
b := bill{
name: name,
items: map[string]float64{},
tip: 0,
}
return b
}
// Format the bill
func (b *bill) format() string {
fs := "Bill breakdown: \n"
var total float64 = 0
// List items
for k, v := range b.items {
fs += fmt.Sprintf("%-25v ...$%v\n", k+":", v)
total += v
}
// Add tip
fs += fmt.Sprintf("%-25v ...$%0.2f\n", "tip:", b.tip)
// Total
fs += fmt.Sprintf("%-25v ...$%0.2f\n", "total:", total+b.tip)
return fs
}
// Update tip
func (b *bill) updateTip(tip float64) {
b.tip = tip
}
// Add an item to the bill
func (b *bill) addItem(name string, price float64) {
b.items[name] = price
}
// save bill
func (b *bill) save() {
data := []byte(b.format())
err := os.WriteFile("bills/normal/"+b.name+".txt", data, 0644)
if err != nil {
panic(err)
}
fmt.Println("bill was saved to file")
}
func getInput(prompt string) (string, error) {
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
input, err := reader.ReadString('\n')
return strings.TrimSpace(input), err
}
func createBill() bill {
name, _ := getInput("Create a new bill name: ")
b := newBill(name)
fmt.Println("Created the bill -", b.name)
return b
}
func parsePrice(s string) float64 {
var price float64
_, err := fmt.Sscanf(s, "%f", &price)
if err != nil {
fmt.Println("the price must be a number")
return 0
}
return price
}
func promptOptions(b bill) {
opt, _ := getInput("Choose option (a - add item, s - save bill, t - add tip): ")
switch opt {
case "a":
name, _ := getInput("Item name: ")
price, _ := getInput("Item price: ")
p := parsePrice(price)
b.addItem(name, p)
fmt.Println("item added -", name, price)
promptOptions(b)
case "t":
tip, _ := getInput("Enter tip amount ($): ")
t := parsePrice(tip)
b.updateTip(t)
fmt.Println("tip added -", tip)
promptOptions(b)
case "s":
b.save()
fmt.Println("saving bill -", b.name)
default:
fmt.Println("that was not a valid option...")
promptOptions(b)
}
}