Skip to content

Instantly share code, notes, and snippets.

@rogfut
Last active July 22, 2018 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rogfut/1ef6d87ea3f094011efdeb1ff8c918a8 to your computer and use it in GitHub Desktop.
Save rogfut/1ef6d87ea3f094011efdeb1ff8c918a8 to your computer and use it in GitHub Desktop.
//cash-register
//https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/
function checkCashRegister(price, cash, cid) {
//reference for currency values
const currency = {
'ONE HUNDRED': 100.00,
'TWENTY': 20.00,
'TEN': 10.00,
'FIVE': 5.00,
'ONE': 1.00,
'QUARTER': 0.25,
'DIME': 0.10,
'NICKEL': 0.05,
'PENNY': 0.01
};
//get register total
const regTotal = () => {
const total = cid.reduce((acc, cur) => acc + cur[1], 0).toFixed(2);
return total;
}
//debugging
console.log('register total is: ' + regTotal());
//object constructors
const change = (status, change) =>({
status,
change
})
const customerHand = {
status: 'OPEN',
change: []
};
//pre-check
let changeDue = cash - price;
if(changeDue == regTotal()) {
return change("CLOSED", cid);
}
if(changeDue > regTotal()) {
return change("INSUFFICIENT_FUNDS", []);
}
//iterate thru cid array right to left
for(var i = cid.length - 1; i >= 0; i--) {
let denomination = cid[i][0];
let amount = cid[i][1];
let count = 0;
//find the right currency amount
while(changeDue >= amount && amount > 0) {
changeDue -= changeDue;
amount -= amount;
count++;
}
if(count > 0) {
customerHand.status = 'OPEN'
customerHand.change.push([denomination, (count * currency[denomination])]);
} else {
customerHand.status = 'INSUFFICIENT_FUNDS'
}
}
console.log(customerHand);
return customerHand;
}
checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["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