-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLunch.js
More file actions
57 lines (47 loc) · 1.75 KB
/
Lunch.js
File metadata and controls
57 lines (47 loc) · 1.75 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
// declare globals
var money = 20;
var lunches = 0;
//display lunch budget
document.getElementById("money").innerHTML = money;
//listen for order
document.getElementById("placeOrder").addEventListener("click", buyLunches);
/*
buys specified number of sandwiches per day at current prices
*/
function buyLunches() {
resetForm();
var day = 0;
// Continue buying sandwiches while there is still money
while (money > 0) {
day++;
var priceToday = getSandwichPrice();
var numberOfSandwiches = document.getElementById("numSandwiches").value;
var totalPrice = priceToday * numberOfSandwiches;
// Check if there's enough money to buy the sandwiches
if (money >= totalPrice) {
money = money - totalPrice;
lunches++;
// Display a message if there's not enough money
document.getElementById("receipt").innerHTML += "<p>On day " + day + ", sandwiches are: $" + priceToday + ". You have $" + money.toFixed(2) + " left.</p>";
} else {
document.getElementById("receipt").innerHTML += "<p>Today, sandwiches are: $" + priceToday + ". You don't have enough money. Maybe your sister will give you some of her sandwich.</p>";
money = 0;
}
}
document.getElementById("receipt").innerHTML += "<p>You bought " + lunches + " lunches this week.</p>";
}
/*
gets the current price of sandwiches
*/
function getSandwichPrice() {
var sandwichPrice = (Math.random() * (5 - 1) + 1).toFixed(2);
return sandwichPrice;
}
/*
resets the game so that a new order can be placed
*/
function resetForm() {
money = 20;
lunches = 0;
document.getElementById("receipt").innerHTML = "";
}