-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrency.js
63 lines (52 loc) · 1.58 KB
/
currency.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
const Currency = {
calculateReal(change, quantityByCoins) {
change = parseInt(change);
let realCount = quantityByCoins[quantityByCoins.length - 1];
if (change > realCount) {
throw new Error(`empty box`);
}
return change;
},
calculateCents(change, quantityByCoins) {
let cents = [50, 25, 10, 5, 1],
count = 0;
let rawCents = parseInt(Math.round((change - parseInt(change)) * 100));
let acumullateCents = [0, 0, 0, 0, 0];
quantityByCoins.pop();
quantityByCoins.reverse();
for (let i = 0; rawCents !== 0; i++) {
count = rawCents / cents[i];
if (count != 0 && count >= 1) {
if (quantityByCoins[i] < parseInt(count)) {
throw new Error(`empty box`);
}
acumullateCents[i] = parseInt(count);
rawCents = rawCents % cents[i];
}
}
return acumullateCents.reverse();
},
validateInputs(change, quantityByCoins) {
if (typeof change !== 'number') {
throw new Error(`missing type number`);
}
if (change < 0) {
throw new Error(`missing number greater than zero`);
}
if (!Array.isArray(quantityByCoins)) {
throw new Error(`missing array of numbers`);
}
if (quantityByCoins.length !== 6) {
throw new Error(`missing array length 6`);
}
quantityByCoins.forEach(coinTotal => {
if (typeof coinTotal !== 'number') {
throw new Error(`missing type number in array`);
}
if (coinTotal < 0) {
throw new Error(`missing number greater than zero in array`);
}
});
}
};
module.exports = Currency;