Skip to content

Instantly share code, notes, and snippets.

@tianmingzuo
Created October 14, 2019 23:16
Show Gist options
  • Select an option

  • Save tianmingzuo/c94bb1eec62c6be9d7abf18b31e5d333 to your computer and use it in GitHub Desktop.

Select an option

Save tianmingzuo/c94bb1eec62c6be9d7abf18b31e5d333 to your computer and use it in GitHub Desktop.
Cash Register: Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument. cid is a 2D array listing available currency. The checkCashRegister()function should always return an object with a status key …
function checkCashRegister(price, cash, cid) {
let billArr = [["ONE HUNDRED", 100], ["TWENTY", 20], ["TEN", 10], ["FIVE", 5],
["ONE", 1], ["QUARTER", 0.25], ["DIME", 0.1], ["NICKEL", 0.05],
["PENNY", 0.01]];
let changeDue = cash - price;
let sumCash = 0;
for(let i=0; i<cid.length; i++){
sumCash += cid[i][1];
}
if(sumCash < changeDue){
return {status: "INSUFFICIENT_FUNDS", change: []};
}
if(sumCash === changeDue){
return {status: "CLOSED", change: cid};
}
let revCid = cid.reverse(); //reverse() method changes the original array(cid)
let changeArr = [];
for(let i=0; i<revCid.length; i++){
let count = 0;
while(revCid[i][1] > 0 && changeDue >= billArr[i][1]){
revCid[i][1] -= billArr[i][1];
changeDue -= billArr[i][1];
changeDue = changeDue.toFixed(2); //toFixed() method returns a string
count++;
}
changeArr.push([billArr[i][0], billArr[i][1]*count]);
}
let finalArr = [];
for(let i=0; i<changeArr.length; i++){
if(changeArr[i][1] !== 0){
finalArr.push(changeArr[i]);
}
}
if(changeDue == 0){ //changeDue is a string, so cannot use "==="
return {status: "OPEN", change: finalArr};
}
//here, although sumCash is enough, but you cannot return the exact change.
return {status: "INSUFFICIENT_FUNDS", change: []};
}
// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.1],
// ["QUARTER", 4.25],
// ["ONE", 90],
// ["FIVE", 55],
// ["TEN", 20],
// ["TWENTY", 60],
// ["ONE HUNDRED", 100]]
//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]]);
//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]]).status);
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]]);
//checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment