Tell us what’s happening:
Hey! Working on Cash Register. Sorry for the really convoluted answer design, def not my best work. It was one of those things where I was getting a bunch of errors because of float rounding and it led me to create this monstrosity. As of now, I’m almost positive test 3 isn’t passing because of some similar float issue. Any idea whats going on with the pennies??
Edit: Solved! Added:
change = Math.round(change * 100)/100
To the loop for pennies and it worked. A little head scratching as to why, but ill take it!
Your code so far
function checkCashRegister(price, cash, cid) {
let change = cash - price;
let origChange = change;
let out = [];
if(change === 0 || onlyEqualPennies(change, cid)){
return {status: "CLOSED",
change: cid};
}else if(change > funds(cid)){
return {status: "INSUFFICIENT_FUNDS",
change: []};
}else{
let numHun = 0;
while(change >= 100 && cid[8][1] > 0){
change -= 100;
cid[8][1] -= 100;
numHun += 100;
}
if(numHun != 0){
out.push(["ONE HUNDRED", numHun]);
}
let numTwenty = 0;
while(change >= 20 && cid[7][1] > 0){
change -= 20;
cid[7][1] -= 20;
numTwenty += 20;
}
if(numTwenty != 0){
out.push(["TWENTY", numTwenty]);
}
let numTen = 0;
while(change >= 10 && cid[6][1] > 0){
change -= 10;
cid[6][1] -= 10;
numTen += 10;
}
if(numTen != 0){
out.push(["TEN", numTen]);
}
let numFive = 0;
while(change >= 5 && cid[5][1] > 0){
change -= 5;
cid[5][1] -= 5;
numFive += 5;
}
if(numFive != 0){
out.push(["FIVE", numFive]);
}
let numOne = 0;
while(change >= 1 && cid[4][1] > 0){
change -= 1;
cid[4][1] -= 1;
numOne += 1;
}
if(numOne != 0){
out.push(["ONE", numOne]);
}
let numQuarter = 0;
while(change >= .25 && cid[3][1] > 0){
change -= .25;
cid[3][1] -= .25;
numQuarter += .25;
}
if(numQuarter != 0){
out.push(["QUARTER", numQuarter]);
}
let numDime = 0;
while(change >= .10 && cid[2][1] > 0){
change -= .10;
cid[2][1] -= .10;
numDime += .10;
}
if(numDime != 0){
out.push(["DIME", numDime]);
}
let numNickel = 0;
while(change >= .05 && cid[1][1] > 0){
change -= .05;
cid[1][1] -= .05;
numNickel += .05;
}
if(numNickel != 0){
out.push(["NICKEL", numNickel]);
}
let numPenny = 0;
while(change > 0 && cid[0][1] > 0){
change -= .01;
cid[0][1] -= .01;
numPenny += .01;
}
if(numPenny != 0){
out.push(["PENNY", numPenny]);
}
console.log({status: "OPEN", change: out});
if(change == 0){
return {status: "OPEN", change: out};
}else{
return {status: "INSUFFICIENT_FUNDS", change: []};
}
}
}
function onlyEqualPennies(cash, cid){
if (funds(cid) === cid[0][1] && cid[0][1] == cash){
return true;
}
}
function funds(arr){
let sum = 0;
arr.forEach(el => sum+=el[1])
return Number(sum.toFixed(2));
}
checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:83.0) Gecko/20100101 Firefox/83.0
.
Challenge: Cash Register
Link to the challenge: