Last active
January 21, 2021 11:41
-
-
Save levchenkod/90cc5cf7dac7028236d3461a48ee907f to your computer and use it in GitHub Desktop.
Fetch currencies rate and get ratio between two currencies
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
/** | |
* @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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: