@ashenm/

Exact Change - Advanced

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
64
65
66
67
68
69
70
71
/**
 * Exact Change
 * https://www.freecodecamp.org/challenges/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 = [];

  // the drawer
  const drawer = {
    TOTAL: 0
  };

  // currency 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
  }

  // balance due
  let balance = cash - price;

  // initialise cid as an object
  cid.forEach(element => {
    drawer.TOTAL += element[1];
    drawer[element[0]] = element[1];
  });

  if (drawer.TOTAL < balance) {
    return 'Insufficient Funds';
  }

  if (drawer.TOTAL === balance) {
    return 'Closed';
  }

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

    const reduction = Math.floor(balance / map[key]) * map[key];

    if (reduction >= drawer[key]) {
      change.push([key, drawer[key]]);
      balance = Math.round((balance - drawer[key]) * 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