-
Notifications
You must be signed in to change notification settings - Fork 0
/
currency-convert.js
58 lines (51 loc) · 1.7 KB
/
currency-convert.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
const axios = require('axios');
const getExchangeRate = async (from, to) => {
try {
const response = await axios.get(`https://api.fixer.io/latest?base=${from}`);
const rate = response.data.rates[to];
if (!rate) {
throw new Error();
} else {
return rate;
}
} catch (e) {
throw new Error(`Unable to get exchange rate for ${from} and ${to}`);
}
};
const getCountries = async (currencyCode) => {
try {
const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
return response.data.map((country) => country.name);
} catch (e) {
throw new Error(`Unable to get countries that use ${currencyCode}`);
}
};
const convertCurrency = (from, to, amount) => {
let countries;
return getCountries(to).then((tempCountries) => {
countries = tempCountries;
return getExchangeRate(from, to);
}).then((rate) => {
const exchangeAmount = rate * amount;
return `${amount} ${from} is worth ${exchangeAmount} ${to}. You can spend these in following countries: ${countries.join(', ')}`
});
};
const convertCurrencyAlt = async (from, to, amount) => {
var countries = await getCountries(to);
var rate = await getExchangeRate(from, to);
const exchangeAmount = rate * amount;
return `${amount} ${from} is worth ${exchangeAmount} ${to}. You can spend these in following countries: ${countries.join(', ')}`
};
convertCurrencyAlt('CAD', 'USD', 100).then((result) => {
console.log(result);
}).catch((e) => {
console.log(e.message);
});
// getExchangeRate('USD', 'CAD').then((rate) => {
// console.log(rate);
// }).catch((e) => {
// console.log(e.message);
// });
// getCountries('EUR').then((list) => {
// console.log(list);
// });