I made the lesson for Build a cash register project and the code seems ok, but the test 12 and 18 don’t pass. ¿What can be happening?
My HTML:
<html>
<head>
</head>
<body>
<input id="cash" type="number" value="0"/>
<button id="purchase-btn" type="button">Change</button>
<p id="change-due"></p>
<script src="script.js"></script>
</body>
</html>
My javascript:
let price = 19.50;
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]
];
const base = [
['PENNY', 0.01],
['NICKEL', 0.05],
['DIME', 0.1],
['QUARTER', 0.25],
['ONE', 1],
['FIVE', 5],
['TEN', 10],
['TWENTY', 20],
['ONE HUNDRED', 100]
];
const totalChange = () => {
let acum = 0;
cid.forEach(item => {
acum+=item[1];
});
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/build-a-cash-register-project/build-a-cash-register
return acum;
}
const button = document.getElementById('purchase-btn');
const div = document.getElementById('change-due');
const calculateChange = () => {
let closed = true;
let input = document.getElementById('cash');
let cash = parseFloat(input.value);
if(cash < price) {
alert("Customer does not have enough money to purchase the item");
}
if(cash.toFixed(2) === price.toFixed(2)) {
div.textContent = "No change due - customer paid with exact cash";
return;
}
let returned = cash-price;
let cashed = [];
let cidReversed = cid.reverse();
base.reverse().forEach((el, index) => {
if(el[1] < parseFloat(returned.toFixed(2)) && returned > 0) { //Entramos si podemos dar cambio
if(cidReversed[index][1] >= returned) { //Nos sobra
let selected = el[1]*Math.floor((returned / el[1]) + 1e-10);
if(selected > 0.005) {
cashed.push([el[0],selected]);
returned -= selected;
if(cidReversed[index][1] > returned + selected) {
closed = false;
}
for(let i = 0; i< 9; i++) {
if(cid[i][0] === el[0]) {
cid[i][1] -= selected;
}
}
}
}
else { //Nos falta
let selected = cidReversed[index][1];
if(selected > 0.005) {
cashed.push([el[0],selected]);
returned -= selected;
for(let i = 0; i< 9; i++) {
if(cid[i][0] === el[0]) {
cid[i][1] = 0;
}
}
}
}
}
});
if(Math.abs(parseFloat(returned.toFixed(2))) === 0.00) {
const word = closed? "CLOSED" : "OPEN";
div.textContent = "Status: " + word;
cashed.forEach(el => {
div.textContent+=" " + el[0] + ": " + "$" + el[1];
})
}
else if(Math.abs(parseFloat(returned.toFixed(2))) > 0) {
div.textContent = "Status: INSUFFICIENT_FUNDS";
}
console.log(cid);
}
button.addEventListener('click', calculateChange);
Thanks in advance.