Skip to content

Instantly share code, notes, and snippets.

@CEOehis
Created August 30, 2020 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CEOehis/2b0aaa8b6767435fb4bdeef454f795b3 to your computer and use it in GitHub Desktop.
Save CEOehis/2b0aaa8b6767435fb4bdeef454f795b3 to your computer and use it in GitHub Desktop.
const DEFAULT_CURRENCY = 'EUR';
const baseURL = 'http://data.fixer.io/api';
const accessToken = 'xxxxxxx';
const currencySymbols = ['USD', 'EUR', 'JPY'];
const symbolsAPIUrl = `${baseURL}/latest?access_key=${accessToken}&symbols=${currencySymbols.join(',')}&format=1`;
const sourceInput = document.getElementById('source');
const targetInput = document.getElementById('target');
const sourceSelect = document.getElementById('source-select');
const targetSelect = document.getElementById('target-select');
let apiCurrencyRates = {};
let baseCurrencyRates = {}
async function initDataSource() {
console.log('initializing data sources...');
try {
const response = await axios.get(symbolsAPIUrl);
console.log('the response', response);
return response.data;
} catch (e) {
console.log('the err', e)
}
}
window.onload = async () => {
const data = await initDataSource();
apiCurrencyRates = data.rates;
setCurrencyAsBase(DEFAULT_CURRENCY);
console.log('the reates', baseCurrencyRates);
// setup event listeners for input changes
sourceInput.addEventListener('input', handleSourceChange);
targetInput.addEventListener('input', handleTargetChange);
// setup event listeners for dropdown changes
sourceSelect.addEventListener('change', handleSourceCurrencyChange);
targetSelect.addEventListener('change', handleTargetCurrencyChange);
}
function handleSourceChange(e) {
const convertedValue = Number((baseCurrencyRates[targetSelect.value] * e.target.value).toFixed(2));
targetInput.value = convertedValue;
}
function handleTargetChange(e) {
const convertedValue = Number((e.target.value / baseCurrencyRates[targetSelect.value]).toFixed(2));
sourceInput.value = convertedValue;
}
function handleSourceCurrencyChange() {
setCurrencyAsBase(sourceSelect.value);
handleSourceChange({target: {value: sourceInput.value}})
}
function handleTargetCurrencyChange() {
setCurrencyAsBase(targetSelect.value);
handleTargetChange({target: {value: targetInput.value}})
}
function setCurrencyAsBase(currency) {
const currencyValue = apiCurrencyRates[currency];
for (const [curr, value] of Object.entries(apiCurrencyRates)) {
baseCurrencyRates[curr] = value / currencyValue;
}
console.log('new base', baseCurrencyRates);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment