@jp2kk2/

exact change

JavaScript

No description

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function checkCashRegister(price, cash, cid) {
  var change = [],
    CID = 0,
    cd = cash - price;
  var denoms = {
    "PENNY": 0.01,
    "NICKEL": 0.05,
    "DIME": 0.1,
    "QUARTER": 0.25,
    "ONE": 1.00,
    "FIVE": 5.00,
    "TEN": 10.00,
    "TWENTY": 20.00,
    'ONE HUNDRED': 100.00,
  };

  for (var i in cid) {
    CID += cid[i][1];
  }

  //Determine if enough change is available.
  CID = Math.round(CID * 100) / 100;
  if (CID == cd) {
    return 'Closed';
  } else if (CID < cd) {
    return 'Insufficient Funds';
  }

  //Determine change due
  //Iterate through cid array from largest to smallest
  cid.reverse();
  for (var j in cid) {
    //var curr=[];
    var amount = denoms[cid[j][0]];
    console.log(cd,amount,cid[j][1]
    );
    console.log (cid[j][1] > 0 && cd - amount >= 0);
    if (cid[j][1] > 0 && cd - amount >= 0) {
      console.log(cd >= cid[j][1]);
      if (cd >= cid[j][1]) {
        change.push([cid[j][0], cid[j][1]]);
        cd = Math.round((cd-cid[j][1])*100)/100;
      } else {
        change.push([cid[j][0], Math.floor(cd/amount)*amount]);
        //lower cd
        cd =Math.round((cd- Math.floor(cd/amount)*amount)*100)/100;
      }
    }
  }
  //If change too large, return Insufficient Funds
  if(cd>0){
    return "Insufficient Funds";
  }
  //return change due
  return change;
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
Native Browser JavaScript