Javascript Cash Register

Date: 2021-09-27

Source: https://stackoverflow.com/questions/38831446/calculating-exact-change-with-javascript

function checkCashRegister(price: number, cash: number, cid: Array<Array<any>>) {
    let change = 100 * (cash - price);
    const moneyValues = [1, 5, 10, 25, 100, 500, 1000, 2000, 10000];
    const amtToReturn = [];

    for (let i = cid.length - 1; i >= 0; i--) {
        let amt = 0;
        while (moneyValues[i] <= change && cid[i][1] > 0 && change > 0) {
            console.log(`subtracting ${moneyValues[i]}`);
            cid[i][1] -= moneyValues[i] / 100; // reduce amount in cid
            change -= moneyValues[i]; // reduce amount from change
            amt += moneyValues[i] / 100; // keep track of how much money was taken out of cid
        }
        if (amt !== 0) {
            // adds record of amount taken out of cid
            amtToReturn.push([cid[i][0], amt]);
        }
    }

    // if there is still some change left over
    if (change !== 0) {
        console.log(change);
        return "Insufficient Funds";
    }

    // if there is any money left in cid, it returns amtToReturn
    for (let j = 0; j < cid.length; j++) {
        if (cid[j][1] > 0) {
            return amtToReturn;
        }
    }

    // if register is empty
    return "Closed";
}

// Example cash-in-drawer array:
// [["PENNY", 1.01], 0
// ["NICKEL", 2.05], 1
// ["DIME", 3.10],   2
// ["QUARTER", 4.25],3
// ["ONE", 90.00],   4
// ["FIVE", 55.00],  5
// ["TEN", 20.00],   6
// ["TWENTY", 60.00],7
// ["ONE HUNDRED", 100.00]]8

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
53820cookie-checkJavascript Cash Register