Last active
April 2, 2019 12:42
-
-
Save gladchinda/248a5a8cf10f873450bba26350170d03 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use your CurrencyConverter API KEY | |
// Set the currency conversion API URL | |
const API_KEY = 'YOUR_API_KEY_HERE'; | |
const API_URL = `https://free.currencyconverterapi.com/api/v6/convert?apiKey=${API_KEY}&compact=ultra`; | |
// Set the base currency (US Dollar in this case) | |
const BASE_CURRENCY = 'USD'; | |
// Set the list of available currencies | |
const AVAILABLE_CURRENCIES = [ | |
'GBP', 'EUR', 'CNY', 'JPY', 'CAD', | |
'AUD', 'NGN', 'ZAR', 'KES', 'INR' | |
]; | |
/** | |
* Fetches the exchange rate of a currency relative to the `BASE_CURRENCY`. | |
* @param {string} currency The currency to convert to | |
* @returns {Promise} A promise that is fulfilled with an array of the format [currency, rate] | |
*/ | |
const exchangeRate = currency => { | |
// The currency conversion symbol | |
// For example: the symbol for NGN will be 'USD_NGN' | |
const symbol = `${BASE_CURRENCY}_${currency}`; | |
// Append the conversion symbol to the API URL and make a request with Fetch | |
// The JSON response will look like this: `{ USD_NGN: 359.999687 }` | |
// Return a promise that is fulfilled with an array of the format [currency, rate] | |
// For example: ['NGN', 359.999687] | |
return fetch(`${API_URL}&q=${symbol}`) | |
.then(response => response.json()) | |
.then(data => [ currency, data[symbol] || null ]); | |
} | |
/** | |
* Fetches the exchange rates of multiple currencies relative to the `BASE_CURRENCY`. | |
* @param {Array} currencies The currencies to convert to from the `BASE_CURRENCY` | |
* @returns {Promise} A promise that is fulfilled with an object map of each currency to exchange rate | |
*/ | |
const fetchExchangeRates = currencies => { | |
// Notice the use of `Array.map(exchangeRate)` to create Promises for each currency's exchange rate | |
// `Promise.all()` is used to execute all the promises in parallel (batch) | |
// When all the promises have been settled, `Array.reduce()` is used to construct the object map | |
// Return a promise that is fulfilled with an object map of each currency to exchange rate | |
return Promise.all(currencies.map(exchangeRate)) | |
.then(rates => { | |
return rates.reduce((data, [ currency, rate ]) => { | |
return { ...data, [currency]: rate }; | |
}, {}); | |
}); | |
} | |
// Fetch the exchange rates for all the listed AVAILABLE_CURRENCIES | |
// `console.log()` the data on fulfillment and `console.error()` on rejection | |
fetchExchangeRates(AVAILABLE_CURRENCIES) | |
.then(console.log, console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment