I keep getting a off by one error in my tests but I can’t find it. Maybe someone else can see it somewhere in there?
function checkCashRegister(price, cash, cid) {
//value of change needed to be returned
let changeValue = cash - price;
let changeRemaining = changeValue + 0;
//cidValue function returns the total amount of money in register rounded to the hundreths bc of floating point errors
function cidValue(cid) {
let total = 0
for(let i = 0; i < cid.length; i++){
total += cid[i][1]
}
return Math.round((100*total))/100
}
//function that returns the least amount of bills/coins in change
function changeValToMoney(changeRemaining, cid){
let currencyValue = [0.01, 0.05, 0.10, 0.25, 1, 5, 10, 20, 100]
let currName = ["PENNY","NICKEL","DIME","QUARTER","ONE","FIVE","TEN","TWENTY","ONE HUNDRED"]
let result = []
let i = 8
let j = 0
while(i > -1){
//if change is greater than current bill
if(changeRemaining > currencyValue[i]){
//if number of currency we're giving is <= the number of bills in register
if(j <= (cid[i][1]/currencyValue[i])){
changeRemaining -= currencyValue[i]
j ++
}
}
if(changeRemaining < currencyValue[i]){
if(j !== 0){
result.push([currName[i], currencyValue[i]*j])
j = 0
i --
} else {
i--
}
}
if(changeRemaining === currencyValue[i]){
result.push([currName[i], currencyValue[i]*(j+1)])
i = -1
}
}
return result
}
//switch that sets Response to the correct values and returns Response
function setStatus(changeValue, cidValue){
if(cidValue > changeValue){
if(changeValToMoney(changeValue, cid) == []){
return "INSUFFICIENT_FUNDS"
}
return "OPEN"
} else if(cidValue == changeValue){
return "CLOSED"
} else if(cidValue < changeValue){
return "INSUFFICIENT_FUNDS"
}
}
Response = {
status: setStatus(changeValue, cidValue(cid)),
change: changeValToMoney(changeValue, cid)
}
return Response
}
Challenge: Cash Register