Build a Cash Register Project - Build a Cash Register

Tell us what’s happening:

Hi FreeCodeCamp Community, this is my first time requesting for an help as I’m stuck, I will continue to look for an solution, but the issues seems that inside my change function, cidCount[num] is not taking away the counts in bigToSmall ary. Therefore it’s not resulting in a depletion of type currency count, meaning my for of will still loop through the currency num even when It should not. Because eventually subtraction will deplete it to 0.

Your code so far

<!-- file: index.html -->
const customerCash = document.getElementById("cash");
const purchase = document.getElementById("purchase-btn");
const customerChange = document.getElementById("change-due");
let cash = 6;
let price = 3.54;

let cid = [
  ['PENNY', 1.01],
  ['NICKEL', 2.05],
  ['DIME', 3.1],
  ['QUARTER', 4.25],
  ['ONE', 90],
  ['FIVE', 55],
  ['TEN', 20],
  ['TWENTY', 60],
  ['ONE HUNDRED', 100]
];

const currencyValue = 
 [ ['PENNY', 0.01],
  ['NICKEL', 0.05],
  ['DIME', 0.1],
  ['QUARTER', 0.25],
  ['ONE', 1],
  ['FIVE', 5],
  ['TEN', 10],
  ['TWENTY', 20],
  ['ONE HUNDRED', 100]]


purchase.addEventListener("click", () => { 
  let cash = customerCash.value;
  if(cash < price){
    return alert("Customer does not have enough money to purchase the item")
  } else if (cash <= price){
    console.log(`${price} = ${cash}`)
    customerChange.innerHTML = "No change due - customer paid with exact cash";
    return
  }
  // gatheredChange()
  changeGiven();
});
const array = [];



const loop = (num) => {
  const result = [];
  for(let i = 0; i < array.length; i++){
  for(let j = 0; j < num.length; j++){
   if(i === j){
   array[i].push(num[j])
  };
  }
  result.push([...array[i]]);
  }

  return result;
  };

// returning the total amount of count for the cid array. 
const countInCid = () => {
  const cidCounts = {};
  cid.forEach((item, index) => {
    const [cidNam, cidNum] = item;
    if(cidNam === currencyValue[index][0]){
      const counts = Math.floor(cidNum/currencyValue[index][1]);
      
      currencyValue[index][1] = parseFloat((cidNum - cidNum));
      if(cidCounts[cidNam]){
        cidCounts[cidNam] += counts;
      }else{
        cidCounts[cidNam] = counts;
      }
    }
  })
  
  return Object.entries(cidCounts) 
}; 
 

const change = () => {
  let cash = customerCash.value;
  let cusChange = parseFloat(100 - 3); 
  const storedCount = {};
  const bigToSmallAry = loop(sorted());
const cidCount = countInCid().reverse();
// prepares array to be sorted. 
 while(cusChange > 0)
cidCount.forEach(([inname, innum], index) => {
  for(const [name, num] of bigToSmallAry){
  if( num <= cusChange && innum > 0){
  const count = Math.min(Math.floor(cusChange/num), innum);
if (inname === storedCount[name]){
    cidCount[index][1] -= count
  };
  // this is where i believe the problem lies. 
   if(innum <= 0){
     bigToSmallAry[index][0];
   }
   
  cusChange = parseFloat((cusChange - (count * num)).toFixed(2));
console.log(`total count ${count}`);
   if(storedCount[name]){
     storedCount[name] += count;
   }else if (count >= 1 && storedCount[name] === bigToSmallAry[name]){
     const addvalue = count * num;
     storedCount[name] = addvalue;
   }else{
     storedCount[name] = count; 
   }
  
  } 
  }
});
console.log(storedCount)
console.log(cidCount)
return storedCount; 
}

 
const gatheredChange = () => {
  let cidNum = []; 
  cid.forEach((el) => {
    cidNum.push(el[1])
  });
  let total = cidNum.reduce((a,b) => a + b, 0).toFixed(2);
  const getnum = Object.entries(change()).map((item) => item);
  while(total > 0)
  for(const [name, num] of cid){
    getnum.forEach((item,index) => {
      const [currentName, currentNum] = item; 
    if(name === currentName && num - currentNum >= 0){
    const subtraction =  num - currentNum.toFixed(2) 
   getnum[index] = [currentName, 0];
    total = parseFloat((total - currentNum)).toFixed(2);
    cid.forEach((item, index) => {
    const [innername, inneritem] = item
    if(innername === name && inneritem === num){
    cid[index] =[innername, subtraction];
    }
      })
    };
    })
  }
  
    return cid;
};



const changeGiven = () => {
const ul = document.createElement('ul');
  const values = Object.entries(change()).reverse();
  values.forEach((item, index)=> {
    customerChange.innerHTML = "";
    const [objName, objNum] = item;
    const list = document.createElement('li')
    list.textContent =`${objName}: ${objNum}`;
    ul.appendChild(list);
  });
  customerChange.appendChild(ul);
};


const sorted = () => {
  const v = currencyValue.map((item) => item[1]);
  const largeToSmall = v.sort((a,b) => b - a  );
  const n = currencyValue.map((item) => item[0]).reverse();
  
   n.forEach((item) => {
     array.push([item]);
   });
  return largeToSmall;
};



/* file: script.js */
const customerCash = document.getElementById("cash");
const purchase = document.getElementById("purchase-btn");
const customerChange = document.getElementById("change-due");
let cash = 6;
let price = 3.54;

let cid = [
  ['PENNY', 1.01],
  ['NICKEL', 2.05],
  ['DIME', 3.1],
  ['QUARTER', 4.25],
  ['ONE', 90],
  ['FIVE', 55],
  ['TEN', 20],
  ['TWENTY', 60],
  ['ONE HUNDRED', 100]
];

const currencyValue = 
 [ ['PENNY', 0.01],
  ['NICKEL', 0.05],
  ['DIME', 0.1],
  ['QUARTER', 0.25],
  ['ONE', 1],
  ['FIVE', 5],
  ['TEN', 10],
  ['TWENTY', 20],
  ['ONE HUNDRED', 100]]


purchase.addEventListener("click", () => { 
  let cash = customerCash.value;
  if(cash < price){
    return alert("Customer does not have enough money to purchase the item")
  } else if (cash <= price){
    console.log(`${price} = ${cash}`)
    customerChange.innerHTML = "No change due - customer paid with exact cash";
    return
  }
  // gatheredChange()
  changeGiven();
});
const array = [];



const loop = (num) => {
  const result = [];
  for(let i = 0; i < array.length; i++){
  for(let j = 0; j < num.length; j++){
   if(i === j){
   array[i].push(num[j])
  };
  }
  result.push([...array[i]]);
  }

  return result;
  };

// returning the total amount of count for the cid array. 
const countInCid = () => {
  const cidCounts = {};
  cid.forEach((item, index) => {
    const [cidNam, cidNum] = item;
    if(cidNam === currencyValue[index][0]){
      const counts = Math.floor(cidNum/currencyValue[index][1]);
      
      currencyValue[index][1] = parseFloat((cidNum - cidNum));
      if(cidCounts[cidNam]){
        cidCounts[cidNam] += counts;
      }else{
        cidCounts[cidNam] = counts;
      }
    }
  })
  
  return Object.entries(cidCounts) 
}; 
 

const change = () => {
  let cash = customerCash.value;
  let cusChange = parseFloat(100 - 3); 
  const storedCount = {};
  const bigToSmallAry = loop(sorted());
const cidCount = countInCid().reverse();
// prepares array to be sorted. 
 while(cusChange > 0)
cidCount.forEach(([inname, innum], index) => {
  for(const [name, num] of bigToSmallAry){
  if( num <= cusChange && innum > 0){
  const count = Math.min(Math.floor(cusChange/num), innum);
if (inname === storedCount[name]){
    cidCount[index][1] -= count
  };
  // this is where i believe the problem lies. 
   if(innum <= 0){
     bigToSmallAry[index][0];
   }
   
  cusChange = parseFloat((cusChange - (count * num)).toFixed(2));
console.log(`total count ${count}`);
   if(storedCount[name]){
     storedCount[name] += count;
   }else if (count >= 1 && storedCount[name] === bigToSmallAry[name]){
     const addvalue = count * num;
     storedCount[name] = addvalue;
   }else{
     storedCount[name] = count; 
   }
  
  } 
  }
});
console.log(storedCount)
console.log(cidCount)
return storedCount; 
}

 
const gatheredChange = () => {
  let cidNum = []; 
  cid.forEach((el) => {
    cidNum.push(el[1])
  });
  let total = cidNum.reduce((a,b) => a + b, 0).toFixed(2);
  const getnum = Object.entries(change()).map((item) => item);
  while(total > 0)
  for(const [name, num] of cid){
    getnum.forEach((item,index) => {
      const [currentName, currentNum] = item; 
    if(name === currentName && num - currentNum >= 0){
    const subtraction =  num - currentNum.toFixed(2) 
   getnum[index] = [currentName, 0];
    total = parseFloat((total - currentNum)).toFixed(2);
    cid.forEach((item, index) => {
    const [innername, inneritem] = item
    if(innername === name && inneritem === num){
    cid[index] =[innername, subtraction];
    }
      })
    };
    })
  }
  
    return cid;
};



const changeGiven = () => {
const ul = document.createElement('ul');
  const values = Object.entries(change()).reverse();
  values.forEach((item, index)=> {
    customerChange.innerHTML = "";
    const [objName, objNum] = item;
    const list = document.createElement('li')
    list.textContent =`${objName}: ${objNum}`;
    ul.appendChild(list);
  });
  customerChange.appendChild(ul);
};


const sorted = () => {
  const v = currencyValue.map((item) => item[1]);
  const largeToSmall = v.sort((a,b) => b - a  );
  const n = currencyValue.map((item) => item[0]).reverse();
  
   n.forEach((item) => {
     array.push([item]);
   });
  return largeToSmall;
};




/* file: styles.css */
*{
  height:auto;
  margin:0auto;
  padding:0auto;
 }

h1{
  text-align: center;
  font-family:'Roboto', sans-serif;
  font-size:35px
}

#change-due{
 display:flex;
 flex-direction:column;
 font-family:'sans-serif', sans-serif;
 padding:auto;
 margin:0 auto;
 color:gray;
 align-items:center;
}

#user-container{
  display:flex;
  flex-direction:column;
  align-items:center;
}

.sub-text{
  display:flex;
  flex-direction:column;
  margin:20px;
  border-bottom:2px gray solid;
font-family:'sans-serif', sans-serif;
}

input{
  width:200px;
  height:20px;
  border-radius:5px;
}

button{
  margin:20px;
  width:100px;
  font-size:20px;
  font-weight:bold;
  font-family:'Roboto', sans-serif;
  border:5px solid yellow;
  border-right: 5px solid gold;
  border-bottom: 5px solid gold;
  background: linear-gradient(140deg,yellow,gold); 
  box-shadow: 5px 5px 5px;
  cursor:pointer;
 
}

button:active{
   border-right: 5px solid yellow;
  border-bottom: 5px solid yellow; 
  border-left:5px solid gold;
  border-top:5px solid gold;
  transform: translateY(1px);
}

#cash-register-container{
 display:flex;
justify-content:center;
margin:auto;
padding:0auto;
width:300px;
border:5px solid black;
}

.top-drawer{
  display:flex;
  flex-direction:row;
  align-self:flex-start;
  border:5px solid green;
  padding-left:10px;
  padding-right:10px;
  font-weight:bold;
  color:white;
  font-size:20px;
  background-color:black;
  height:25px;
}

.body-drawer{
  display:flex;
  border:5px solid green;
  height:auto;
  width:150px;
  padding:auto;
}

.body-drawer span {
  display:flex;
  flex-direction:column;
}

ul{ 
  padding-right:35px;
  text-align: center;
  list-style-type: none;

}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36 Edg/134.0.0.0

Challenge Information:

Build a Cash Register Project - Build a Cash Register

can you edit your post and put your actual html here?

<!DOCTYPE html> 
<html lang="en">
  <head>
    <title>Cash Register</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    </head>
    <body>
      <h1 name="title">Cash Register</h1>
        <div id="change-due"></div>
         <span id="user-container">
          <span>
           <lable class="sub-text">Enter cash from</label> 
           customer: 
           </span>
           <div id="change-due"></div>
            <input id="cash" name="cash" type="number" required>
             <span>
               <button id="purchase-btn" type="button" name="purchase">Purchase</button>
               </span>
         </span>
          <div id="cash-register-container">
            <div class="top-drawer">
              <div id="total-amount">Total: $3.26</div>
              </div>
              <div class="body-drawer">
                <div id="change-in-drawer"><strong>Change in drawer:</strong> 
                  <span id="pennies">pennies:</span>
                  <span id="nickle">nickle:</span>
                  <span id="dime">dime:</span>
                  <span id="quarter">quarter:</span>
                  <span id="dollar">dollar:</span>
                  <span id="five-dollar">five:</span>
                  <span id="ten-dollar">ten:</span>
                  <span id="twenty-dollar">twenty:</span>
                  <span id="hundreds">hundreds:</span>
                </div>
              </div>
            <div class="bottom-drawer"><div class="drawer-nob"></div></div>
          </div>
  <script src="script.js"></script>
   </body>
  </htm>

It’s my fault for not checking properly before posting, I couldn’t seem to find the pencil, edit button, so I put the html in my reply .

if you add this below your code in the js file you can see one by one what your output is for each test.

Things I notice, you do not have STATUS in any of the outputs, you may want to look into it

console.log("\nTest #9");
price = 11.95;
document.querySelector("#cash").value = 11.95;
document.querySelector("#purchase-btn").click();
console.log("actual", document.querySelector("#change-due").innerText);
console.log("expected", "No change due - customer paid with exact cash");

console.log("\nTest #11");
price = 19.5;
document.querySelector("#cash").value = 20;
cid = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]];
document.querySelector("#purchase-btn").click();
console.log("actual", document.querySelector("#change-due").innerText);
console.log("expected", "Status: OPEN QUARTER: $0.5");

console.log("\nTest #12");
price = 3.26;
document.querySelector("#cash").value = 100;
cid = [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]];
document.querySelector("#purchase-btn").click();
console.log("actual", document.querySelector("#change-due").innerText);
console.log("expected", "Status: OPEN TWENTY: $60 TEN: $20 FIVE: $15 ONE: $1 QUARTER: $0.5 DIME: $0.2 PENNY: $0.04");

console.log("\nTest #14");
price = 19.5;
document.querySelector("#cash").value = 20;
cid = [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];
document.querySelector("#purchase-btn").click();
console.log("actual", document.querySelector("#change-due").innerText);
console.log("expected", "Status: INSUFFICIENT_FUNDS");

console.log("\nTest #16");
price = 19.5;
document.querySelector("#cash").value = 20;
cid = [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];
document.querySelector("#purchase-btn").click();
console.log("actual", document.querySelector("#change-due").innerText);
console.log("expected", "Status: INSUFFICIENT_FUNDS");

console.log("\nTest #18");
price = 19.5;
document.querySelector("#cash").value = 20;
cid = [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]];
document.querySelector("#purchase-btn").click();
console.log("actual", document.querySelector("#change-due").innerText);
console.log("expected", "Status: CLOSED PENNY: $0.5");

I really appreciate you taking the time to give me this advice. It seems that not having Status could be a problem. I will find what that means and what the things are to do so that it will work.