-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransactionFactory.js
62 lines (52 loc) · 1.77 KB
/
transactionFactory.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
var transaction = function(spec) {
var that = {};
that.makeChange = function ( ) {
if(checkPayment()) {
logCoins(countCoins());
}
};
function checkPayment( ) {
if(spec.payment < spec.cost) {
console.log("Please enter an additional $" + (spec.cost - spec.payment).toFixed(2));
} else if(isNaN(spec.cost) || isNaN(spec.payment) || spec.cost < 0 || spec.payment < 0) {
console.log("Please enter positive numbers only.");
} else {
return true;
}
}
function countCoins() {
var changeRemaining = spec.payment * 100 - spec.cost * 100,
coinCount = [0, 0, 0, 0],
coinValue = [25, 10, 5, 1];
for(var i = 0; i < coinCount.length; i++) {
if(changeRemaining >= coinValue[i]) {
coinCount[i] = Math.floor(changeRemaining / coinValue[i]);
changeRemaining = changeRemaining % coinValue[i];
}
}
return coinCount;
}
function logCoins(coinCount) {
var coinName = ["Quarters", "Dimes", "Nickels", "Pennies"],
output = "\n";
for(var i = 0; i < coinName.length; i++) {
if(coinCount[i] > 0) {
output += coinCount[i] + " " + coinName[i] + "\n";
}
}
console.log(output);
}
return that;
};
var transaction1 = transaction({cost: 0.43, //logs correctly
payment: 1});
transaction1.makeChange();
var transaction2 = transaction({cost: -0.43, //positives only
payment: 1});
transaction2.makeChange();
var transaction3 = transaction({cost: "a", //numbers only
payment: 1});
transaction3.makeChange();
var transaction4 = transaction({cost: 1, //need more money
payment: 0.43});
transaction4.makeChange();