Last active
November 20, 2019 14:12
-
-
Save i-anshuman/c12224d99f19445b9b05814d92c11c78 to your computer and use it in GitHub Desktop.
FreeCodeCamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const denominationTypes = { | |
'PENNY': 0.01, | |
'NICKEL': 0.05, | |
'DIME': 0.1, | |
'QUARTER': 0.25, | |
'ONE': 1, | |
'FIVE': 5, | |
'TEN': 10, | |
'TWENTY': 20, | |
'ONE HUNDRED': 100 | |
}; | |
const checkCashRegister = (price, cash, cid) => { | |
const totalCash = Number(cid.map(c => c[1]).reduce((a, b) => a + b).toFixed(2)); | |
let due = cash - price; | |
if (due > totalCash) { | |
return { | |
status: 'INSUFFICIENT_FUNDS', | |
change: [] | |
} | |
} | |
else if (due === totalCash) { | |
return { | |
status: 'CLOSED', | |
change: cid | |
} | |
} | |
else if (due < totalCash) { | |
const units = cid.map(c => c[0]); | |
const amounts = cid.map(c => c[1]); | |
let changes = []; | |
for (let i = amounts.length -1; i >= 0; i--) { | |
if (amounts[i] <= due) { | |
changes.push([units[i], amounts[i]]); | |
due = (due - amounts[i]).toFixed(2); | |
} | |
else if (amounts[i] >= due) { | |
const value = denominationTypes[units[i]]; | |
const q = parseInt(due / value); | |
if (q == 0) { | |
continue; | |
} | |
const r = (due % value).toFixed(2); | |
changes.push([units[i], (q * value)]); | |
due = (due - (q * value)).toFixed(2); | |
} | |
} | |
if (due == 0) { | |
return { | |
status: 'OPEN', | |
change: changes | |
} | |
} | |
else { | |
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]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment