@ashenm/

Exact Change - Intermediate

JavaScript

Specimen code solution for freeCodeCamp advanced algorithm scripting challenge.

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
/**
* Exact Change
* Returns change due in relation to arguments provided 
*
* Ashen Gunaratne
* [email protected]
*
*/

function checkCashRegister(price, cash, cid) {

  // Here is your change, ma'am.
  const change = [];

  // denomination map
  const map = {
    'ONE HUNDRED' : 100,
    'TWENTY'      : 20,
    'TEN'         : 10,
    'FIVE'        : 5,
    'ONE'         : 1,
    'QUARTER'     : 0.25,
    'DIME'        : 0.10,
    'NICKEL'      : 0.05,
    'PENNY'       : 0.01
  };

  const total = cid.reduce((aggregate, counter) => aggregate + counter[1], 0);

  const drawer = Array.prototype.concat.apply([], cid);

  let balance = cash - price;

  if (total < balance) {
    return 'Insufficient Funds';
  }

  if (total === balance) {
    return 'Closed';
  }

  Object.keys(map).forEach(key => {

    const counter = drawer[drawer.indexOf(key) + 1];
    const reduction = Math.floor(balance / map[key]) * map[key];

    if (reduction >= counter) {
      change.push([key, counter]);
      balance = Math.round((balance - counter) * 100) / 100;
    } else if (reduction > 0) {
      change.push([key, reduction]);
      balance = Math.round((balance - reduction) * 100) / 100;
    }

  });

  return (balance === 0) ? change : 'Insufficient Funds';

}

// test here
checkCashRegister(19.50, 20.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