Last active
May 16, 2020 12:36
-
-
Save martin-mok/880a4ddd1fbf7e810b878db2c36ce675 to your computer and use it in GitHub Desktop.
FreeCodeCamp: Cash Register
This file contains hidden or 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
| function checkCashRegister(price, cash, cid) { | |
| function floatPrecisionCorrection(x){ | |
| return Math.round(x*100)/100; | |
| } | |
| let result={status:null,change:[]}; | |
| let changeTotal=floatPrecisionCorrection(cash-price); | |
| let cidTotal=floatPrecisionCorrection(cid.reduce((a,e)=>a+e[1],0)); | |
| if(changeTotal==cidTotal){ | |
| result.status="CLOSED"; | |
| result.change=cid; | |
| return result; | |
| } | |
| if(changeTotal>cidTotal){ | |
| result.status="INSUFFICIENT_FUNDS"; | |
| return result; | |
| } | |
| let hash=Object.create(null); | |
| hash["PENNY"]=0.01; | |
| hash["NICKEL"]=0.05; | |
| hash["DIME"]=0.1; | |
| hash["QUARTER"]=0.25; | |
| hash["ONE"]=1; | |
| hash["FIVE"]=5; | |
| hash["TEN"]=10; | |
| hash["TWENTY"]=20; | |
| hash["ONE HUNDRED"]=100; | |
| let changeback= cid.reduceRight(function(a,e){ | |
| let changeEachUnit=Math.min(e[1],floatPrecisionCorrection(hash[e[0]]*Math.floor(changeTotal/hash[e[0]]))); | |
| if(changeEachUnit>0){ | |
| changeTotal=floatPrecisionCorrection(changeTotal-changeEachUnit); | |
| a.push([e[0],changeEachUnit]); | |
| } | |
| return a; | |
| },[]); | |
| if(changeTotal>0){ | |
| result.status="INSUFFICIENT_FUNDS"; | |
| return result; | |
| } | |
| result.status="OPEN"; | |
| result.change=changeback; | |
| return result; | |
| } | |
| console.log(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