Can Someone please help…
I have tried to come up with a solution multiple times, but always failed at some testcase.
This time i have come up with a solution to this cash register problem, but i am still failing at two testcases and unable to grasp the why…
Here’s my code:
function checkCashRegister(price, cash, cid) {
var change;
var status;
const coins = [
["ONE HUNDRED", 100],
["TWENTY", 20],
["TEN", 10],
["FIVE", 5],
["ONE", 1],
["QUARTER", 0.25],
["DIME", 0.1],
["NICKEL", 0.05],
["PENNY", 0.01],
]
// calculating change
change = Math.abs(cash - price);
console.log(change)
// cidSum
let cidSum = Math.round( cid.map(item => item[1])
.reduce((a, b) => a + b, 0)
* 100) / 100;
// if cash-in-drawer is less than the change due
if (cidSum < change) {
status = "INSUFFICIENT_FUNDS";
change = []
}
// else if cash-in-drawer is equal to the change due.
else if (cidSum == change) {
status = "CLOSED";
change = [...cid]
}
// else: cash-in-drawer is more to the change due.
else {
status = "OPEN";
var rev_cid = [...cid].reverse();
var changeList = [];
for (let i=0; i<coins.length; i++) {
var val = coins[i][1];
// console.log(coins[i][0], val, rev_cid[i][1])
var mul = 0;
while (change - val >= 0 && change >= val) {
console.log('val', val, change)
change -= val;
mul += 1;
change = Math.round(change * 100) / 100;
}
if (val*mul){
changeList.push([coins[i][0], val*mul])
}
}
change = changeList
}
return {
'status': status,
'change': change
};
}
Test Cases:
// fail
// should return {status: "INSUFFICIENT_FUNDS", change: []}
checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
// // fail
// // should return {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}
// 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]])
// handled
// // return {status: "OPEN", change: [["QUARTER", 0.5]]}.
// 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]])
// handled
// // return {status: "CLOSED", change: [...].
// checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])