Tell us what’s happening:
I am getting this error, i dont know what is wrong with my code
ERROR:
Failed: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]])
should return {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}
.
My code:
function checkCashRegister(price, cash, cid) {
const currencyUnits = [
["PENNY", 1],
["NICKEL", 5],
["DIME", 10],
["QUARTER", 25],
["ONE", 100],
["FIVE", 500],
["TEN", 1000],
["TWENTY", 2000],
["ONE HUNDRED", 10000]
];
let changeDue = (cash - price) * 100; // Convert to cents
let remainingChange = changeDue; // Track remaining change
let change = [];
let totalCid = 0;
for (let i = 0; i < cid.length; i++) {
totalCid += cid[i][1] * 100; // Convert to cents
}
if (changeDue > totalCid) {
return { status: "INSUFFICIENT_FUNDS", change: [] };
} else if (changeDue === totalCid) {
return { status: "CLOSED", change: cid };
} else {
for (let i = currencyUnits.length - 1; i >= 0; i--) {
const unitName = currencyUnits[i][0];
const unitValue = currencyUnits[i][1];
const availableAmount = cid[i][1] * 100; // Convert to cents
if (remainingChange >= unitValue) {
const numberOfUnits = Math.floor(availableAmount / unitValue);
if (numberOfUnits > 0) {
const changeAmount = Math.min(
remainingChange,
numberOfUnits * unitValue
);
change.push([unitName, changeAmount / 100]); // Convert back to dollars
remainingChange -= changeAmount; // Update remainingChange
// Update cid array
cid[i][1] -= changeAmount / 100; // Convert back to dollars
}
}
}
if (remainingChange > 0) {
return { status: "INSUFFICIENT_FUNDS", change: [] };
}
return { status: "OPEN", change };
}
}
// Example usage
const result = 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]
]);
console.log(result);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
Challenge: JavaScript Algorithms and Data Structures Projects - Cash Register
Link to the challenge: