Advertisement
maymunskoa

Cash Register //from FreeCodeCamp Algorithm//

Jan 23rd, 2022
1,184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function checkCashRegister(price, cash, cid) {
  2.   let change = cash * 100 - price * 100;
  3.   let ncid = cid.map((x) => Number(Math.round(x[1] * 100)));
  4.   let returnObject = { status: null, change: [] };
  5.  
  6.   const denominations = [
  7.     ['PENNY', 1],
  8.     ['NICKEL', 5],
  9.     ['DIME', 10],
  10.     ['QUARTER', 25],
  11.     ['ONE', 100],
  12.     ['FIVE', 500],
  13.     ['TEN', 1000],
  14.     ['TWENTY', 2000],
  15.     ['ONE HUNDRED', 10000],
  16.   ];
  17.  
  18.   for (let i = denominations.length - 1; i >= 0; i--) {
  19.     returnObject.change.unshift([denominations[i][0], 0]);
  20.     if (change < denominations[i][1]) {
  21.       continue;
  22.     } else if (change >= denominations[i][1]) {
  23.       while (change >= denominations[i][1]) {
  24.         if (ncid[i] - denominations[i][1] < 0) {
  25.           console.log(ncid[i]);
  26.           break;
  27.         }
  28.         change -= denominations[i][1];
  29.         ncid[i] -= denominations[i][1];
  30.         returnObject.change[0][1] += denominations[i][1];
  31.         console.log(change);
  32.       }
  33.     }
  34.   }
  35.   console.log(change);
  36.   console.log(ncid);
  37.   returnObject.change = returnObject.change
  38.     .map((x) => [x[0], x[1] / 100])
  39.     .sort((a, b) => b[1] - a[1]);
  40.   if (change > 0) {
  41.     returnObject.status = 'INSUFFICIENT_FUNDS';
  42.     returnObject.change = [];
  43.   } else if (ncid.reduce((a, b) => a + b) === 0) {
  44.     returnObject.status = 'CLOSED';
  45.   } else {
  46.     returnObject.status = 'OPEN';
  47.     returnObject.change = returnObject.change.filter((x) => x[1] !== 0);
  48.   }
  49.   return returnObject;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement