JavaScript Cash Register

Hi,

I am struggling with the JavaScript Cash Register. My loop works for a couple of iterations but then the results start becoming unexpected. So I guess my logic is bad but I don’t know how to fix it. I’ve been trying for weeks so would really appreciate any help you can provide. Thank you.

The test I am trying to pass is this one:

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

The test should return the following:

{status: “OPEN”, change: [[“TWENTY”, 60], [“TEN”, 20], [“FIVE”, 15], [“ONE”, 1], [“QUARTER”, 0.5], [“DIME”, 0.2], [“PENNY”, 0.04]]}

My code returns:

[‘TWENTY’, 60], [‘TEN’, 20], [‘FIVE’, 5], [‘FIVE’, 10], [‘FIVE’, 15], [‘ONE’, 1], [‘QUARTER’, 0.25], [‘QUARTER’, 0.5], [‘DIME’, 0.1], [‘DIME’, 0], [‘PENNY’, 0.01], [‘PENNY’, 0.02], [‘PENNY’, 0.03], [‘PENNY’, 0.04]

The TWENTY 60 and TEN 20 match up but then it starts going wrong.

My code:

function checkCashRegister(price, cash, cid) {
  console.log(`price is: ${price}`);
  console.log(`cash given is: ${cash}`);

  // ========= Total In Drawer ======================
  let cidTotalTimesOneHundred = 0;
  let cidArrayInCents = [];

  for (let i = 0; i < cid.length; i++) {
    let cidTimesOneHundred = cid[i][1] * 100; // Here we are getting the cash values from the cid (cash in drawer) array so that we can add them up. We multiply each number by 100 because JavaScript doesn't handle numbers with decimal points very well. Then we divide by 100 later to get the numbers back to normal
    cidTotalTimesOneHundred = cidTotalTimesOneHundred + cidTimesOneHundred; // Adding up the cid (cash in drawer)

    cidArrayInCents.push([cid[i][0], cidTimesOneHundred.toFixed(2)]); // toFixed(2) limits numbers to 2 decimal places
  }

  let cidTotal = cidTotalTimesOneHundred / 100; // dividing the cid total so that it isn't 100 times too big
  console.log(`money in drawer total is: ${cidTotal}`);

  // =============== Change Due =============================
  let changeTimesOneHundred = cash * 100 - price * 100;
  let change = changeTimesOneHundred / 100;
  console.log(`change due is: ${change}`);

  // =============== Return Change =============================

  if (cidTotal < change) {
    console.log({ status: "INSUFFICIENT_FUNDS", change: [] });
    return { status: "INSUFFICIENT_FUNDS", change: [] };
  } else if (cidTotal === change) {
    console.log({ status: "CLOSED", change: cid });
    return { status: "CLOSED", change: cid };
  } else {
    const comparisonArray = [
      ["ONE HUNDRED", 10000],
      ["TWENTY", 6000],
      ["TEN", 2000],
      ["FIVE", 500],
      ["ONE", 100],
      ["QUARTER", 25],
      ["DIME", 10],
      ["NICKEL", 5],
      ["PENNY", 1],
    ];

    cid = cid.reverse();

    cidArrayInCents = cidArrayInCents.reverse();

    // ============ trying again ====================================

    let newArr = [];

    for (let i = 0; i < comparisonArray.length; i++) {
      let value = 0;

      while (
        // while change is greater than than or equal to the amounts in the comparisonArray array:

        changeTimesOneHundred >= comparisonArray[i][1] &&
        changeTimesOneHundred > 0
      ) {
        console.log(`changeTimesOneHundred is ${changeTimesOneHundred}`);

        // minus the current iteration amount in comparisonArray from the change due:

        changeTimesOneHundred = changeTimesOneHundred - comparisonArray[i][1];
        value = value + comparisonArray[i][1] / 100;

        console.log(`comparisonArray[i][1] is ${comparisonArray[i][1]}`);

        console.log(`value times one hundred is ${value * 100}`);
        if (value !== 0) {
          newArr.push([comparisonArray[i][0], value]);
        }
      }
    }

    console.log(`{status: "OPEN", change: ${newArr}}`);
    return { status: "OPEN", change: newArr };
  }
}

You keep switching back and forth between dollars and cents. I would stay in cents until the very end. I would be suspicious that you have some issues in you repeated conversion between the two.

1 Like

Where is the link to the challenge? Also, are you certain that each of the figures in the comparisonArray [] is correct?

2 Likes

Good catch on the comparison array!

1 Like

Sorry. Forgot the link to the challenge:

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register

Thank you for the advice!

I’ve changed it all to cents and wow… that comparisonArray is embarrassing! I’ve corrected the figures and now my output is completely wrong, which is good because I was confused on how my previous output was getting some things correct and some not but now it makes sense.

So I’m pretty sure my for/while loop logic is wrong then. I’m not even sure I can articulate how to make it work with words. I’ll keep trying. Thanks again!

Updated code:

function checkCashRegister(price, cash, cid) {
  console.log(`price is: ${price}`);
  console.log(`cash given is: ${cash}`);

  // ========= Total In Drawer ======================
  let cidTotalTimesOneHundred = 0;
  let cidArrayInCents = [];

  for (let i = 0; i < cid.length; i++) {
    let cidTimesOneHundred = cid[i][1] * 100; // Here we are getting the cash values from the cid (cash in drawer) array so that we can add them up. We multiply each number by 100 because JavaScript doesn't handle numbers with decimal points very well. Then we divide by 100 later to get the numbers back to normal
    cidTotalTimesOneHundred = cidTotalTimesOneHundred + cidTimesOneHundred; // Adding up the cid (cash in drawer)

    cidArrayInCents.push([cid[i][0], cidTimesOneHundred.toFixed(2)]); // toFixed(2) limits numbers to 2 decimal places
  }

  let cidTotal = cidTotalTimesOneHundred;
  console.log(`money in drawer total is: ${cidTotal}`);

  // =============== Change Due =============================
  let changeTimesOneHundred = cash * 100 - price * 100;
  let change = changeTimesOneHundred;
  console.log(`change due is: ${change}`);

  // =============== Return Change =============================

  if (cidTotal < change) {
    console.log({ status: "INSUFFICIENT_FUNDS", change: [] });
    return { status: "INSUFFICIENT_FUNDS", change: [] };
  } else if (cidTotal === change) {
    console.log({ status: "CLOSED", change: cid });
    return { status: "CLOSED", change: cid };
  } else {
    const comparisonArray = [
      ["ONE HUNDRED", 10000],
      ["TWENTY", 2000],
      ["TEN", 1000],
      ["FIVE", 500],
      ["ONE", 100],
      ["QUARTER", 25],
      ["DIME", 10],
      ["NICKEL", 5],
      ["PENNY", 1],
    ];

    cid = cid.reverse();

    cidArrayInCents = cidArrayInCents.reverse();

    // ============ trying again ====================================

    let newArr = [];

    for (let i = 0; i < comparisonArray.length; i++) {
      let value = 0;

      while (
        // while change is greater than than or equal to the amounts in the comparisonArray array:

        changeTimesOneHundred >= comparisonArray[i][1] &&
        changeTimesOneHundred > 0
      ) {
        console.log(`changeTimesOneHundred is ${changeTimesOneHundred}`);

        // minus the current iteration amount in comparisonArray from the change due:

        changeTimesOneHundred = changeTimesOneHundred - comparisonArray[i][1];
        // value = value + comparisonArray[i][1] / 100;
        value = value + comparisonArray[i][1];

        console.log(`comparisonArray[i][1] is ${comparisonArray[i][1]}`);

        console.log(`value times one hundred is ${value * 100}`);
        if (value !== 0) {
          newArr.push([comparisonArray[i][0], value]);
        }
      }
    }

    console.log(`{status: "OPEN", change: ${newArr}}`);
    return { status: "OPEN", change: newArr };
  }
}

Hello, I`m getting close to this exercise, just finished debugging, I’ve noticed that the array starts outside of the function a lot and this is probably going to be my path as well.
Here is what I found on Git Hub.

https://github.com/Manish-Giri/FreeCodeCamp/blob/master/curriculum/challenges/english/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.english.md

1 Like

My code feels so messy when I see how other people do it! Good luck with your cash register robheyays! It’s tough!

I’ve managed to pass 1 more test thanks to the advice I received yesterday. Now the only test left is to return {status: "INSUFFICIENT_FUNDS", change: []} when there is enough change in the register, but the denominations make it impossible