Problem
I’m having a problem with the Cash Register project. The code returns the exact expected output but for some reason some tests fail.
My code
function checkCashRegister(price, cash, cid) {
let change = [];
const unitValues = {
"PENNY": 0.01,
"NICKEL": 0.05,
"DIME": 0.1,
"QUARTER": 0.25,
"ONE": 1,
"FIVE": 5,
"TEN": 10,
"TWENTY": 20,
"ONE HUNDRED": 100
}
let requiredChange = cash - price;
let cidWorth = 0;
cid.forEach(val => cidWorth += val[1]);
cidWorth = Math.round(cidWorth * 100) / 100;
if (cash >= requiredChange) {
cid.reverse().forEach(unit => {
let result = calcChange(unit);
//console.log(result);
result != undefined ? change.push(result) : null;
})
}
function defineStatus () {
if ((cidWorth - (cash - price)) > 0) {
return 'OPEN';
} else if ((cidWorth - (cash - price)) == 0) {
change = cid;
return 'CLOSED';
} else {
change = [];
return 'INSUFFICIENT_FUNDS';
}
};
function calcChange (_unit) {
let currentUnit = {
value: unitValues[_unit[0]],
available: _unit[1]
};
let unitsRequired = Math.floor(requiredChange / currentUnit.value);
let cashRequired = unitsRequired * currentUnit.value;
if (unitsRequired > 0 && currentUnit.available >= requiredChange)
{
requiredChange = Math.round((requiredChange - cashRequired) * 100) / 100;
return [_unit[0] , cashRequired];
}
else if (unitsRequired > 0 && currentUnit.available >= currentUnit.value)
{
requiredChange = Math.round((requiredChange - currentUnit.available) * 100) / 100;
return [_unit[0] , currentUnit.available];
};
};
let status = defineStatus(status);
let finalResult = {status: status , change: change.reverse()};
console.log(finalResult);
return finalResult;
}
checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);
I’m using Firefox Developer Edition 101.0b9 (64-bit), and the same occurs in Google Chrome 101.0.4951.67 64 Bits.
Solution
Turns out that some values returned were indeed wrong, although they were really difficult to detect (comparing with all the other activities of the course).
Conclusion
Thanks for all those who took some time to take a look!