Skip to content

Instantly share code, notes, and snippets.

@alihammad-gist
Last active April 17, 2016 19:07
Show Gist options
  • Save alihammad-gist/9b084e2fc0c1cb818b513e3ce2fa4443 to your computer and use it in GitHub Desktop.
Save alihammad-gist/9b084e2fc0c1cb818b513e3ce2fa4443 to your computer and use it in GitHub Desktop.
function checkCashRegister(price, cash, cid) {
const units = [
{unit: 'ONE HUNDRED', cents: 10000},
{unit: 'TWENTY', cents: 2000},
{unit: 'TEN', cents: 1000},
{unit: 'FIVE', cents: 500},
{unit: 'ONE', cents: 100},
{unit: 'QUARTER', cents: 25},
{unit: 'DIME', cents: 10},
{unit: 'NICKEL', cents: 5},
{unit: 'PENNY', cents: 1},
];
type cashDrawer = {
hash:{
[k:string]: number
}
total: number
};
const drawer: cashDrawer = cid.reduce((prev:cashDrawer, curr) => {
const unit = curr[0], dollars = curr[1];
let hash = prev.hash;
prev.total += dollars * 100;
switch(unit) {
case 'ONE HUNDRED': hash[unit] = dollars / 10000; break;
case 'TWENTY': hash[unit] = dollars / 2000; break;
case 'TEN': hash[unit] = dollars / 1000; break;
case 'FIVE': hash[unit] = dollars / 500; break;
case 'ONE': hash[unit] = dollars; break;
case 'QUARTER': hash[unit] = Math.ceil(dollars * 100)/25 ; break;
case 'DIME': hash[unit] = Math.ceil(dollars * 100)/10; break;
case 'NICKEL': hash[unit] = Math.ceil(dollars * 100)/5; break;
case 'PENNY': hash[unit] = Math.ceil(dollars * 100); break;
}
return prev;
}, { total : 0, hash: {} });
console.log(drawer);
const getFromDrawer = (unit, amount) => {
if (drawer[unit] < amount) {
return drawer[unit]
} else {
return amount;
}
}
const centsToNotes = (cents: number) => {
let res = [];
for (let i = 0; i < units.length && cents > 0; i+=1) {
let notes = cents / units[i].cents | 0;
if (notes) {
notes = getFromDrawer(units[i].unit, notes);
res.push([
units[i].unit,
notes * (units[i].cents / 100)
]);
cents -= notes * units[i].cents;
}
}
if (cents > 0) {
return [];
} else {
return res;
}
}
const change =
}
// Example cash-in-drawer array:
// Denominations dollar cent/penny
//=========================================================================
// [["PENNY", 1.01], 1/100
// ["NICKEL", 2.05], 5/100
// ["DIME", 3.10], 10/100
// ["QUARTER", 4.25], 25/100
// ["ONE", 90.00], 1
// ["FIVE", 55.00], 1 * 5
// ["TEN", 20.00], 1 * 10
// ["TWENTY", 60.00], 1 * 20
// ["ONE HUNDRED", 100.00]] 1 * 100
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]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment