JSFiddle - React, Tailwind, and code Playground

by Bhaumik Mehta

HTML

<h2> JavaScript Puzzle Solution </h2>

<p>I have written it as, user can provide his method and the code will find the method and will return the result or will fail silently. Try to change the method. Select any of the provided calculation method.</p>
<div id="puzzle1">Puzzle 1 answer is : <span id="answer1"></span>

</div>
<br />
<hr>
<em> Solution provided by <strong><a href="http://www.indidev.us" title="Bhaumik Mehta">Bhaumik Mehta</a></strong></em>

JavaScript

/****************************************************************************************
 ********************************** Puzzle 1 ********************************************
 ****************************************************************************************/


function Calculator(source) {

    this.Calculate = function (method, value) {

        var $Term = parseFloat(value.Term),
            $APR = parseFloat(value.APR),
            $VehicleCost = parseFloat(value.VehicleCost),
            $CLDInsurance = parseFloat(value.CLDInsurance),
            method = method.trim();

        for (key in source) {

            if (source.hasOwnProperty(key)) {

                if (key.trim() == method) {

                    /** Convert String into the calculation **/
                    var $MonthlyInterestRate = eval(source.MonthlyInterestRate),
                        $FinAmt = eval(source.FinAmt),
                        $Factor = eval(source.Factor),
                        $MonthlyPayment = eval(source.MonthlyPayment),

                        /* Create variable based on method name provided by user and then return calculation */
                        $Result = eval('$' + method);

                    return $Result.toFixed(2);
                }
            }
        }
    }
}

var carPaymentCalc = new Calculator({
        "MonthlyPayment": "$Factor*$MonthlyInterestRate/($Factor-1)*$FinAmt",
        "Factor": "Math.pow(1+$MonthlyInterestRate,$Term)",
        "MonthlyInterestRate": "$APR/100/12",
        "FinAmt": "$VehicleCost+$CLDInsurance"
});

var newCalculation = carPaymentCalc.Calculate("MonthlyPayment", {
       "Term": 36,
        "APR": 2.9,
        "VehicleCost": 10000,
        "CLDInsurance": 200
});

document.getElementById('answer1').innerHTML = '$' + newCalculation;