Tell us what’s happening:
My code works correctly for other inputs however for the test where [“PENNIES”, 0.04] is expected as the last element in the array, it returns “PENNIES”, 0.03 instead. Im not sure why since the algorithm works correctly for all other values. Also, where it says “i–” inside the for loop instead of inside the bracket to declare it, I tried to put it in the bracket the normal way but I think it causes a runtime error since the for loop won’t work at all like that.
Your code so far
function checkCashRegister(price, cash, cid) {
let output = { status: "", change: [] };
let change = cash - price;
let cashVals = [
{ name: 'PENNY', val: 0.01, quant: 0},
{ name: 'NICKEL', val: 0.05, quant: 0},
{ name: 'DIME', val: 0.10, quant: 0},
{ name: 'QUARTER', val: 0.25, quant: 0},
{ name: 'ONE', val: 1.00, quant: 0},
{ name: 'FIVE', val: 5.00, quant: 0},
{ name: 'TEN', val: 10.00, quant: 0},
{ name: 'TWENTY', val: 20.00, quant: 0},
{ name: 'ONE HUNDRED', val: 100.00, quant: 0}
];
let changeGiven = [];
// Get total
let totalCid = 0;
for(let i = 0; i < cid.length; i++)
{
totalCid += cid[i][1];
}
totalCid = Math.round(totalCid * 100) / 100;
// Handle obvious insufficient funds
if (totalCid < change) {
output.status = 'INSUFFICIENT_FUNDS';
return output;
}
// Handle exact change
if (totalCid == change) {
output.status = 'CLOSED';
output.change = cid;
return output;
}
for(let i = 0; i < cashVals.length;i++)
{
cashVals[i].quant = cid[i][1] / cashVals[i].val;
cashVals[i].quant = Math.round(cashVals[i].quant * 100) / 100;
console.log(cashVals[i].quant);
}
let val = 0;
for(let i = cashVals.length; i > 0;)
{
i--
while(cashVals[i].quant > 0 && change >= cashVals[i].val)
{
change -= cashVals[i].val;
cashVals[i].quant--;
val += cashVals[i].val;
}
if(val > 0){
changeGiven.push([cashVals[i].name , val])
val = 0;
output.status = 'CLOSED';
}
}
console.log(changeGiven);
if (changeGiven.length < 1 || change > 0)
{
output.status = 'INSUFFICIENT_FUNDS';
return output;
}
console.log(output.status);
console.log(output.change);
// Here is your change, ma'am.
output.status = 'OPEN';
output.change = changeGiven;
return output;
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]
checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/