So yersterday after putting off the last js project (the cash register) off for a couple of months because it looked hard, I finally decided to tackle it to get the js Certificate. Although in hindsight, it seems so logical and easy how this cash register works, it did take me a couple of hours to figure it out, partly due to the fact that i hadn’t written so js in a while. However after some persistence and starting fresh at least twice, I finally completed it without any cheesy code and got the js Certificate! Big thanks to FCC for the great curriculum! Here my code for anyone who cares, and feel free to give me some tip and tricks:
function checkCashRegister(price, cash, cid) {
const UNIT = [["PENNY", 1], ["NICKEL", 5], ["DIME", 10], ["QUARTER", 25], ["ONE", 100], ["FIVE", 500], ["TEN", 1000], ["TWENTY", 2000], ["ONE HUNDRED", 10000]]
let change = Math.round(cash*100) - Math.round(price*100)
let return_statement = {status : ""
}
let totalValueInDrawer = 0
let change_statement = []
let totalValueTaken = 0
for (let i = cid.length - 1; i > -1; i -= 1) {
let valueInDrawer = cid[i][1]
let unitValue = UNIT[i][1]
let unitLabel = UNIT[i][0]
let amountOfCoinsInDrawer = Math.round(valueInDrawer*100) / unitValue
totalValueInDrawer += (amountOfCoinsInDrawer * unitValue)
var valueSubstracted = 0
while (((change - unitValue) >= 0) && (amountOfCoinsInDrawer > 0) ){
change -= unitValue
amountOfCoinsInDrawer -= 1
valueInDrawer -= unitValue
valueSubstracted += unitValue
totalValueTaken += unitValue
}
if (valueSubstracted > 0){
change_statement.push([unitLabel, (valueSubstracted/100)])
}
return_statement['change'] = [...change_statement]
}
console.log()
if ((Math.round(cash*100) - Math.round(price*100)) < totalValueInDrawer) {
// console.log(totalValueTaken/100)
// console.log((Math.round(cash*100) - Math.round(price*100))/100)
if ((totalValueTaken/100) == ((Math.round(cash*100) - Math.round(price*100))/100)) {
return_statement['status'] = "OPEN"
}
else{
return_statement['status'] = "INSUFFICIENT_FUNDS"
return_statement['change'] = []
}
}
else if ((Math.round(cash*100) - Math.round(price*100)) > totalValueInDrawer) {
return_statement['status'] = "INSUFFICIENT_FUNDS"
return_statement['change'] = []
}
else {
return_statement['status'] = "CLOSED"
return_statement['change'] = [...cid]
}
console.log(return_statement)
return return_statement
}