Exact Change - So Messy!

Hey guys, it took me a very long time to finish coding this.
It’s most likely VERY non-optimized, but it’s working and was able to pass the challenge. I am fairly sure I did a lot of unnecessary coding and going around in circles, which is why I would like to hear some feedback on how I can improve. :slight_smile:

Your feedback is much appreciated!

Repl.it Link

// THIS TOOK ME FOREVER
function checkCashRegister(price, cash, cid) {
  var totalChange = 0; // Total cash in register
  var cashInRegister = {
    "PENNY" : { value: 0.01, amount: 0 },
    "NICKEL" : { value: 0.05, amount: 0 },
    "DIME" : { value: 0.1, amount: 0 },
    "QUARTER" : { value: 0.25, amount: 0 },
    "ONE" : { value: 1, amount: 0 },
    "FIVE" : { value: 5, amount: 0 },
    "TEN" : { value: 10, amount: 0 },
    "TWENTY" : { value: 20, amount: 0 },
    "ONE HUNDRED" : { value: 100, amount: 0 }
  };
  var returnChange = // Return string. This is cheating.
  [["PENNY", 0],
  ["NICKEL", 0],
  ["DIME", 0],
  ["QUARTER", 0],
  ["ONE", 0],
  ["FIVE", 0],
  ["TEN", 0],
  ["TWENTY", 0],
  ["ONE HUNDRED", 0]];
  for (i=0; i<cid.length; i++) { totalChange += cid[i][1]; } // Calculate total cash
  for (i=0; i<cid.length; i++) { cashInRegister[cid[i][0]].amount = currAmount(cid[i][0],cid[i][1]); } // Populate the cashInRegister with all the money we have as an Object
  if ((cash - price) == totalChange) { // If the change is same as what we've got, close shop
    return "Closed";
  } else if (price > totalChange) { // If change is more than we have, Insufficient Funds
    return "Insufficient Funds";
  } else { // If none of the above, lets do this
    var changeLeft = Number(Math.round((cash - price) + 'e2') + 'e-2'); // Set up how much we have to return in change
    while (changeLeft >= 0) { 
      restart: // This is where we return
      for (i=Object.keys(cashInRegister).length-1; i>=0; i--) { // Reverse iterate through the bills and coins
        if (changeLeft >= cashInRegister[cid[i][0]].value && cashInRegister[cid[i][0]].amount !== 0) { // If the change is bigger than the specific bill/coin ($3.75 > $1)
          changeLeft = Number(Math.round((changeLeft - cashInRegister[cid[i][0]].value) + 'e2')+'e-2'); // Subtract the value from the change
          cashInRegister[cid[i][0]].amount--; // Lower the amount of above coin/note
          returnChange[i][1] += cashInRegister[cid[i][0]].value; // Add what we've given as change to returnChange
          break restart; // Re-start the loop
        } else if (changeLeft === 0) { // If nothing is left to return
          for (i=returnChange.length-1; i>=0; i--) { // Iterate through returnChange (This is reverse because the array re-indexes when you splice)
            if (returnChange[i][1] === 0) { // Seek for 0 values
              returnChange.splice(i,1); // Remove it from the array
            }
          }
          return returnChange.reverse(); // Return the change in reversed order
        }
      }
    }
  }
  // Here is your change, ma'am.
}

function currAmount(currency,amount) { // This is to calculate the amount of each coin/note
  var retAmount = 0;
  switch (currency) {
    case "PENNY":
      retAmount = (amount / 0.01);
      break;
    case "NICKEL":
      retAmount = (amount / 0.05);
      break;
    case "DIME":
      retAmount = (amount / 0.1);
      break;
    case "QUARTER":
      retAmount = (amount / 0.25);
      break;
    case "ONE":
      retAmount = (amount / 1);
      break;
    case "FIVE":
      retAmount = (amount / 5);
      break;
    case "TEN":
      retAmount = (amount / 10);
      break;
    case "TWENTY":
      retAmount = (amount / 20);
      break;
    case "ONE HUNDRED":
      retAmount = (amount / 100);
      break;
  }
  return Math.round(retAmount);
}

checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
// [["QUARTER", 0.50]]

I am on this exact challenge! I knew I wasn’t being efficient so I took a break to read up on functional programming.

What is the question of that challenge may I ask?

The challenge

Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument.

cid is a 2D array listing available currency.

Return the string "Insufficient Funds" if cash-in-drawer is less than the change due. Return the string "Closed" if cash-in-drawer is equal to the change due.

Otherwise, return change in coin and bills, sorted in highest to lowest order.

How do you format your code like that?
When I try to use it, it gives me this comment looking courier new font.

	function checkCashRegister( purchasePrice, amountReceived, cashInDrawer ) {
			var result;
			
			var change   = getChange( purchasePrice, amountReceived );
			var totalCid = getTotalCashInDrawer( );
			
			//================================
			// Return 'Insufficient Funds'
			//================================
			if( change > totalCid ) {
				result = "Insufficient Funds";
			
			//================================
			// Return 'Close'
			//================================
			} else if( change == totalCid ) {
				result = "Closed";
				
			//================================
			// Return Exact Change
			// Or Not Enough Change
			//================================
			} else {
				result = getReturnChange( change );
			}
			
			return result;
		}
		
		
		//==========================================================================		
		// Retrieve Change in all their denomination
		//==========================================================================
		function getReturnChange( change ) {
			var result = new Array( );
			var index = 0;
			var amount;
			
			var tChange = change * 100;			//Get rid of all the decimals for decimal precision purposes.
			var denomination = new Array( );
						
			for( i = 0; i < cashInRegister.length; i++ ) {
				denomination.push( cashInRegister[i][0] * 100 );
			}
			
			do {
				var tempResult = new Array( );
					
				if( tChange >= ( cashInRegister[index][0] * 100 ) ) 
				{	
					amount = Math.floor( tChange / ( cashInRegister[index][0] * 100 ) );
					
					if( isDenominationEnough( cashInRegister[index], amount ) ) {
						tChange -= amount * ( cashInRegister[index][0] * 100 );
						tempResult = [ [ cashInRegister[index][0], amount ] ];
						result.push( tempResult );
					}
				}
				
				index++;
			} while( index < cashInRegister.length );
			
			if( tChange != 0 ) { result = "Not Enough Change"; }
			return result;
		}

		//==========================================================================		
		// Check available denomination - see if there is enough $100 bills to give
		//==========================================================================
		function isDenominationEnough( arry, neededAmount ) {
			var result;
			
			arry[1] >= neededAmount ? result = true : result = false;
	
			return result;
		}


		//==========================================================================		
		// Retrieve the difference between the purchase price and amountReceived
		//==========================================================================
		function getChange( purchasePrice, amountReceived ) {
			return ( amountReceived - purchasePrice ).toFixed( 2 );
		}
		
		
		//==========================================================================		
		// Get summation of all the total in the cash register
		//==========================================================================
		function getTotalCashInDrawer( ) {
			var total = 0.0;
			
			for( i = 0; i < cashInRegister.length; i++ ){
				var denomination = cashInRegister[i][0];
				var amount       = cashInRegister[i][1];
				
				total += denomination * amount;
			}
			
			return (total).toFixed( 2 );
		}

With the magic of markdown of course :slight_smile:
```
Surround your code with grave accents like this.
```

Or inline `like this`

1 Like

Thanks :3

I wrote the code not for the challenge. Don’t know if it will pass. LOL
Added extra in there, “Don’t have enough change to give” :smiley:

I think I forgot to do one last thing on it. Sorting it in order.