JavaScript Algorithms and Data Structures Projects - Cash Register

Hi,

looking to aid my understanding. The code below works but my understanding of what is happening in the while loop is trailing. I understand that i’ve set curr to equal elem[0] which would mean it takes the value of “penny” for example. but when i am deducting the amount taking from the drawer to give back in change, and adding to variable amount. why does it accept adding with curr( which would be a string) as opposed to the currSum which would be an integer?

  **Your code so far**
const currencyUnit = {
"PENNY": 1,
"NICKEL": 5,
"DIME": 10,
"QUARTER": 25,
"ONE": 100,
"FIVE": 500,
"TEN": 1000,
"TWENTY": 2000,
"ONE HUNDRED": 10000
}

function checkCashRegister(price, cash, cid) {

let changeSum = cash * 100 - price * 100;
let changeSumCheck = changeSum;
let change = [];
let status = '';

let cidSum = 0;
let filteredCid = cid.filter(elem => elem[1] !== 0).reverse();

filteredCid.forEach(elem => {
  let curr = elem[0];
  let currSum = elem[1] * 100;
  cidSum += currSum;
  let amount = 0;
  while (changeSum >= currencyUnit[curr] && currSum > 0) {
    amount += currencyUnit[curr];
    changeSum -= currencyUnit[curr];
    currSum -= currencyUnit[curr];
  }
  if (amount !== 0) {
    change.push([curr, amount / 100]);
  }
});

if (changeSum > 0) {
  status = 'INSUFFICIENT_FUNDS';
  change = [];
} else if (changeSum == 0 && changeSumCheck == cidSum) {
  status = 'CLOSED';
  change = cid;
} else {
  status = 'OPEN';
}
return { 'status': status, 'change': change };
}

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]]);

Challenge: JavaScript Algorithms and Data Structures Projects - Cash Register

Link to the challenge:

Hi @zak_ali ,

What a confusing wording lol :smile:

Because you are not adding a string but a number, currencyUnit[curr] resolves to a number, that is how you access the value of a dictionary

For example:

const curr = "PENNY"
const value = currencyUnit[curr] // number

By the way, the overall idea and code is very good.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.