Hey everyone!
I’ve recently tried to build the Cash Register Project for the JavaScript algorithms course.
However, the code runs perfectly fine if I run it on my PC locally and it catches all the requirements. But the freeCodeCamp tests fail (4 of the last 5 requirements to be precise).
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
<title>Cash Register</title>
</head>
<body>
<script>
let price = 3.26;
let cash = 0.00;
let cid = [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.1],
["QUARTER", 4.25],
["ONE", 90],
["FIVE", 55],
["TEN", 20],
["TWENTY", 60],
["ONE HUNDRED", 100]
];
let amount = [
100.00,
20.00,
10.00,
5.00,
1.00,
0.25,
0.10,
0.05,
0.01
]
cid = cid.reverse();
</script>
<div id="content">
<h1>Register</h1>
<span id="span">Item price: $19.5</span><br/><br/>
<input id="cash" type="number" placeholder="Enter paid value">
<br/>
<button id="purchase-btn" onclick="calculate(cid, price)">Purchase</button>
<br/><br/>
<div id="change-due"></div>
</div>
</body>
</html>
function calculate(cid, price){
price = parseFloat((price).toFixed(2));
let cash = 0.00;
cash = parseFloat(document.getElementById("cash").value).toFixed(2);
let diff = parseFloat(cash - price).toFixed(2);
let sum = 0.00;
let statusOpen = "Status: OPEN";
let statusClosed = "Status: CLOSED";
let statusIns = "Status: INSUFFICIENT_FUNDS";
let changeDue = document.getElementById("change-due");
for (let i = 0; i < cid.length; i++) {
sum += parseFloat(parseFloat(cid[i][1]).toFixed(2));
}
//ALERTS
if(diff < 0){
alert("Customer does not have enough money to purchase the item");
return;
}
else if(diff == 0){
changeDue.innerText = ("No change due - customer paid with exact cash");
return;
}
//STATUS
if(sum > diff){
changeDue.innerText = statusOpen;
}
else if(sum < diff || sum == 0){
changeDue.innerText = statusIns;
return;
}
else if(sum == diff){
changeDue.innerText = statusClosed;
}
//ALGORITHM
for(let i = 0; i < amount.length; i++){
let count = 0;
while(diff >= amount[i] && cid[i][1] >= amount[i]){
if(diff == amount[i] && cid[i][1] == amount[i]){
changeDue.innerText = statusClosed;
diff = (diff - amount[i]).toFixed(2);
cid[i][1] = (cid[i][1] - amount[i]).toFixed(2);
count++;
}
else{
diff = (diff - amount[i]).toFixed(2);
cid[i][1] = (cid[i][1] - amount[i]).toFixed(2);
count++;
}
}
if(count > 0){
if(sum < diff || i == (amount.length - 1) && diff > 0.00){
changeDue.innerText = statusIns;
return;
}
else{
changeDue.innerText += `\n${cid[i][0]}: $${amount[i] * count}`;
}
}
}
}
This is my entire code (without CSS). Hopefully someone can help me with that. Thanks in advance!