Tell us what’s happening:
Basically this is my my cash register project which works and passes all the tests. I am interested to know if my approach of using
Math.round(change * 100) / 100;
after every math operation is correct solution because if i were not to use it the results would give back strange numbers like : 74.99999995 etc…
Also are there any solutions on how i could tidy up the code to make it more readable or more efficient
Your code so far
function checkCashRegister(price, cash, cid) {
const clone = JSON.parse(JSON.stringify(cid));
let change = cash - price;
change = Math.round(change * 100) / 100;
const database = {
"ONE HUNDRED": 100,
"TWENTY": 20,
"TEN": 10,
"FIVE": 5,
"ONE": 1,
"QUARTER": 0.25,
"DIME": 0.1,
"NICKEL": 0.05,
"PENNY": 0.01
};
let changeArr = [];
for(let i = clone.length - 1; i >=0; i--) {
let changeCur = 0;
while(change >= database[clone[i][0]] && clone[i][1] > 0) {
change -= database[clone[i][0]];
change = Math.round(change * 100) / 100;
clone[i][1] -= database[clone[i][0]];
clone[i][1] = Math.round(clone[i][1] * 100) / 100;
changeCur += database[clone[i][0]];
changeCur = Math.round(changeCur * 100) / 100;
}
if(changeCur !== 0) changeArr.push([clone[i][0], changeCur])
}
if(change > 0) {
return {
'status': 'INSUFFICIENT_FUNDS',
'change': []
}
} else if(clone.every(el => el[1] === 0)) {
return {
'status': 'CLOSED',
'change': cid
}
} else {
return {
'status': 'OPEN',
'change': changeArr
}
}
}
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]]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register