1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| function checkCashRegister(price, cash, cid) { var change = cash - price; var newCid = [...cid] newCid.reverse() var unitArr = [0.01, 0.05, 0.1, 0.25, 1, 5, 10, 20, 100].reverse() var newCidValue = []; for (let i = 0; i < newCid.length; i++) { newCidValue.push(newCid[i][1]) } var cidTotal = newCidValue.reduce((a, b) => a + b)
if (change === cidTotal) { return { status: "CLOSED", change: cid } } if (change > cidTotal) { return { status: "INSUFFICIENT_FUNDS", change: [] } } if (change < cidTotal) { let newCidNum = [] for (let i = 0; i < newCid.length; i++) { newCidNum.push(newCid[i][1] / unitArr[i]) }
let final = [] for (let i = 0; i < newCid.length; i++) { let n = parseInt(change / unitArr[i]) if (n <= newCidNum[i]) { final.push([newCid[i][0], n * unitArr[i]]) change = change - n * unitArr[i] change = change.toFixed(2) } else { final.push(newCid[i]) change = change - newCid[i][1] change = change.toFixed(2) } }
let newFinal = [] let newTotal = [] for (let i = 0; i < final.length; i++) { if (final[i][1] !== 0) { newFinal.push(final[i]) newTotal.push(final[i][1]) } }
if (newTotal.reduce((a, b) => a + b).toFixed(2) == cash - price) { return { status: "OPEN", change: newFinal }; } else { return { status: "INSUFFICIENT_FUNDS", change: [] } } }
}
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]]));
|