Hi there !
I’ve tried multiple solutions, thinking about a precision problem but I’m not sure anymore. I pass all tests except one. I would like a little hint on my mistake.
Oh and my code construction is pretty messy, I’m sorry for that but if you have any tips to improve, feebacks are welcome !
function checkCashRegister(price, cash, cid) {
var change = cash - price;
let ticket = {status: "", change: []};
const values = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000];
function howMuchDrawer(array) {
return array.reduce((acc, current) => {
return acc + current[1];
}, 0);
}
// Basics solutions, no enough money or exact change
if (change > howMuchDrawer(cid)) {
ticket.status = "INSUFFICIENT_FUNDS";
} else if (change == howMuchDrawer(cid)) {
ticket.status = "CLOSED";
ticket.change = cid;
// Actual problem. I've tried to *100 in case of a precision mistake, but the behavior didn't change.
} else {
change = Math.round((cash - price) * 100);
cid.forEach(el => el[1] = Math.round(el[1] * 100));
for (var i = cid.length - 1; i >= 0; i--) {
var dueChange = 0;
// Here is the problem, my algo think that I can return money for the 5th test.
while (cid[i][1] > 0 && change >= values[i]) {
change -= values[i];
cid[i][1] -= values[i];
dueChange += values[i];
}
if (dueChange) {
ticket.status = "OPEN";
ticket.change.push([cid[i][0], dueChange]);
}
}
ticket.change.forEach(el => el[1] = (el[1] / 100));
}
return ticket;
}
Challenge link : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register


