Can anyone help me with my solution for the challenge, I know I’m getting close, if I console.(i[0], i[1]) during the while loop, the console gives me the information i need separately as individual denominations repeated. The only trouble I’m having is I want to sum the total of each denomination and then reset the counter before it moves onto the next denomination. If i set just a general count outside the loop it will just count to the total change number and wont give me the total per denomination.
function checkCashRegister(price, cash, cid) {
var register = [
["ONE HUNDRED", 100, cid[8][1]],
["TWENTY", 20, cid[7][1]],
["TEN", 10, cid[6][1]],
["FIVE", 5, cid[5][1]],
["ONE", 1, cid[4][1]],
["QUARTER", 0.25, cid[3][1]],
["DIME", 0.10, cid[2][1]],
["NICKEL", 0.05, cid[1][1]],
["PENNY", 0.01, cid[0][1]]
]
var insuf = "INSUFFICIENT_FUNDS";
var closed = "CLOSED";
var open = "OPEN";
var totalRegister = register.reduce((sum, i) => sum + i[2], 0).toFixed(2);
var answer = {status: "INSUFFICIENT_FUNDS", change: []};
var change = Math.abs(price - cash);
var newArr = []
var count = 0
if (totalRegister == change) {
answer.status = closed;
answer.change = cid;
} else if (totalRegister < change) {
answer.status = insuf
} else if (totalRegister > change) {
for (var i of register) {
while (change >= i[1] && i[2] > 0) {
change = Math.round(change*100)/100;
change -= i[1];
i[2] -= i[1];
var subArr = []
subArr.push(i[0], i[1]);
}
if (subArr) {
newArr.push(subArr)
}
}
if (change == 0) {
answer.status = open
answer.change = newArr
}
}
return answer
}
console.log(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]]));
This logs the below on the console;
{ status: 'OPEN',
change:
[ [ 'TWENTY', 20 ],
[ 'TEN', 10 ],
[ 'FIVE', 5 ],
[ 'ONE', 1 ],
[ 'QUARTER', 0.25 ],
[ 'DIME', 0.1 ],
[ 'DIME', 0.1 ],
[ 'PENNY', 0.01 ] ]
Can anyone help point me in the right direction? The code is also logging the Dime denomination twice and I can’t work out why.