Reputation: 33
I have this earning calculator function
EarningsCalculator.prototype.computeEarning = function (rate, investedValue) {
var earnings = {};
var currentState = investedValue;
for (var i = 0; i <= 5; i++) {
earning=currentState*rate;
currentState = currentState + earning;
earnings[i] = currentState;
}
return earnings;
}
It takes an "invested value" and based on a give rate, it calculates earning, which in this case is limited to 5 years with a for loop. What I need is to calculate earnings[0]
at 1 year interval and earnings[1]
through earnings[4]
at a 5 year interval.
So with Invested value of 1000 and interest rate of 10%, it returns the following output for 5 years
Year1 = 1100
Year2 = 1210
Year3 = 1331
Year4 = 1464.1
Year5 = 1610.51
What I want is this
Year1 = 1100
Year5 = 1610.51
Year10 = 2593.74246
Year15 = 4177.248169
Year20 = 6727.499949
Upvotes: 3
Views: 860
Reputation: 314
You could use a modulus on the years in your for loop to add only those years that are divisible by 5. Then add another or condition for the first year:
function EarningsCalculator (rate, investedValue) {
var earnings = {};
var currentState = investedValue;
var YEAR_INTERVAL = 5;
var YEARS_COMPOUNDING = 20;
for (var i = 1; i <= YEARS_COMPOUNDING; i++) {
earning=currentState*rate;
currentState = currentState + earning;
if (i % YEAR_INTERVAL == 0 || i == 1) {
earnings[i] = currentState;
}
}
return earnings;
}
var earnings = [];
earnings = EarningsCalculator(.10,1000);
console.log(earnings);
That should log the correct values to your object in the console.
One advantage of this is being able to change your yearly interval as a variable rather than hardcoding those values in an array for different periods of time.
JSFiddle: https://jsfiddle.net/kgill/zgmrtmhg/1/
Upvotes: 1
Reputation: 386883
You could use the formular for calculation the earnings.
function getPeriodicCompounding(p, r, t) {
return Math.pow(r + 1, t) * p;
}
var originalPrincipalSum = 1000,
interestRate = 0.1,
times = [1, 5, 10, 15, 20]
times.forEach(function (time) {
console.log(time, getPeriodicCompounding(originalPrincipalSum, interestRate, time));
});
Upvotes: 3