2
\$\begingroup\$

I am creating a simple currency converter, which accepts only 3 currencies. Everything is working fine, just my code doesn't look so good.

I tried to wrap it revealing module pattern, and still looks poor. So my question is should I use if/else statements inside fetch, or should I, maybe, rewrite the code, using ES6 classes and OOP? Please review and suggest.

var request = new Request('test.json', {
    method: 'GET', 
    mode: 'cors', 
    redirect: 'follow',
    headers: new Headers({
        'Content-Type': 'application/json'
    })
});

//initate app
 function calculateCurrency() {
    let currVal  = Number(placeholderCurrency.value),
        firstValue = getSelected(selectCurrency).value,
        secondValue = getSelected(currentCurrency).value;

    //fetch data from api
     fetch(request).then(resp=> resp.json())
        .then((data) => {
            const mainObj = data.result;
            const eur = mainObj['eur'].pro;
            const usd = mainObj['usd'].pro;
            const rsd = 1;


            function calculusBiger(cur1,cur2,val1,val2) {   
                if(firstValue == cur1 && secondValue == cur2) {
                        calculatedCurrency.value = currVal*(val1*val2);
                    }
            }

            function calculusSmaller(cur1,cur2,val1,val2) {
                if(firstValue == cur1 && secondValue == cur2) {
                    calculatedCurrency.value = currVal*(val1/val2);
                }
            }


            calculusSmaller("eur","usd",eur,usd);
            calculusBiger("eur","rsd",eur,rsd);
            calculusBiger("usd","rsd",usd,rsd);
            calculusSmaller("usd","eur",usd,eur);
            calculusSmaller("rsd","eur",rsd,eur);
            calculusSmaller("rsd","usd",rsd,usd);

            return (function() {
            return   {
            first:firstValue,
            second:secondValue,
            val:currVal 
            }
        }());

        })
        .catch((err) =>{
            console.log(err);
        })
}


    //get option selected
    function getSelected(elem) {
            let opts = elem.children;
            for(i=0; i < opts.length; i++) {
            if(opts[i].selected) {
                 return opts[i];
            }

        }
    }
\$\endgroup\$
  • \$\begingroup\$ why does the second callback to .then() call calculusSmaller() 4 times and calculusBiger()twice, and in the given order? When is calculateCurrency() called? My guess is button click or some other UI interaction... Please edit your post to include this information \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Oct 25 '17 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.