Hello,
For the Cash Register problem, I was focusing on what I thought to be the most difficult part, which was being able to calculate what kind of change and how much I can return according to the CID.
For example, if I have to give back 1 dollar change, but I only have enough pennies, I should be able to return the change in pennies.
I finally got it to work, but instead of the array giving the total sum of the dollar value, I am getting each dollar value pushed into the array.
For example: I have to return 0.5 in change. My function returns:
[ [ ‘QUARTER’, 0.25 ], [ ‘QUARTER’, 0.25 ] ]
Instead of
[ [ ‘QUARTER’, 0.5 ]]
I’m wondering how I can return the sum of the change if it is the same dollar value
Here’s my code so far (apologies for poor formatting and potential pointless code):
function checkCashRegister(price, cash, cid) {
let currency = {
"ONE HUNDRED": 100,
"TWENTY":20,
"TEN": 10,
"FIVE": 5,
"ONE": 1,
"QUARTER":0.25,
"DIME": 0.1,
"NICKEL": 0.05,
"PENNY": 0.01,
}
//calculating change
let change = cash -price;
//function to find total of cash in drawer
let cidfun = cid.reduce((acc, num)=>{
return acc +=num[1];
},0)
//because js sucks at maths
let totalCID= cidfun.toFixed(2);
let changeArray=[]
//calculating the smallest values I can use to give back change and putting into an array
let fachange = change;
for (let key in currency){
if (fachange>currency[key]){
changeArray.push(key);
}
}
//the array for the total change I the CID is able to give
let resArr = [];
//function to return correct change if cid is able
cid=cid.reverse()
cid.map(val => {
if (val[1]> change){
while (val[1]>0 && change>=currency[val[0]]){
val[1]-=currency[val[0]]
change-= currency[val[0]]
resArr.push([val[0],currency[val[0]]])
}
}
})
console.log(resArr)
let result = {"status": "OPEN", "change": resArr}
}
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]]);