Skip to content

Instantly share code, notes, and snippets.

@levchenkod
Last active January 21, 2021 11:41
Show Gist options
  • Save levchenkod/90cc5cf7dac7028236d3461a48ee907f to your computer and use it in GitHub Desktop.
Save levchenkod/90cc5cf7dac7028236d3461a48ee907f to your computer and use it in GitHub Desktop.
Fetch currencies rate and get ratio between two currencies
/**
* @function fetchRates
* @description fetch currencies rate
* @param {string} [url='https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json'] - currencies rate api endpoint
* @returns {promise}
* @example
* let rates = [];
* fetchRates().then(newRates => {
* rates = newRates;
* });
*/
const fetchRates = (url) => {
return fetch(url || 'https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json')
.then(res => res.json())
.catch(console.error);
};
/**
* @function getRatio
* @description get currencies ratio
* @param {array} rates - list of rates data
* @param {string} currencySlugA
* @param {string} currencySlugB
* @returns {number}
* @example
* let ratio = getRatio(ratesList, 'EUR', 'USD'); // 1.2108000780045032
*/
const getRatio = (rates, currencySlugA, currencySlugB) => {
let aData = rates.filter(i => i.cc === currencySlugA)[0];
let bData = rates.filter(i => i.cc === currencySlugB)[0];
if(!aData){
throw(`Invalid value for $currencySlugA: ${currencySlugA}`);
}
if(!bData){
throw(`Invalid value for currencySlugB: ${currencySlugB}`);
}
return Number(aData.rate) / Number(bData.rate);
};
@levchenkod
Copy link
Author

Usage example:

fetchRates()
    .then((rates) => {
        const ratio = getRatio(rates, 'EUR', 'USD');
        console.log({ratio});
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment