<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;
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.