Junior
Junior

Reputation: 77

Calculate multiple values ​in a loop

In a future income calculator, I need to display the data accumulated in 5 years, 10 years and 15 years.

In this account, I take the value of the monthly contributions, after 12 months, I apply the annual profitability, with that the final value of one year is concluded.

To get the value of the second year, I take the initial value of the sum of the 12 months and make the sum with the value of the 12 months with profitability.

The account is as follows ...

contributions = 536,06;
profitability = 4.27;
fixedYearVal = 536,06 * 12; // 6.432,72
profitabilityVal =  (profitability / 100) * fixedYearVal;
fixedYearprofitability = fixedYearVal + profitabilityVal;

With that, I discover the first year with profitability. The value for the second year will be (secondYear = fixedYearVal + fixedYearprofitability). The final amount for the second year will be

percentSecondYear = (profitability / 100) * secondYear;
finalSecondYear = percentSecondYear + secondYear;

And the value of the third year is going to be

thirYear = finalSecondYear + fixedYearVal;
percentthirdYear = (profitability / 100) * thirYear;
finalThirdyear = percentthirdYear + thirYear;

Anyway, as I said, I need it for 5 years, 10 years and 15 years, and I can't imagine any other way than to make thousands of lines, I thought about doing it with a for in Javascript but with this data boo I found myself lost . 😢

Upvotes: 0

Views: 152

Answers (1)

UnfocusedDrive
UnfocusedDrive

Reputation: 191

I threw something together. Maybe this can help you get started. The idea is 1) set some base values 2) throw it through a loop of n years you want to calculate. 3) return the final results in an array so you can see a year by year

// Calculate the next year
const caclNextYear = (lastYear, fixedYearVal, profitability) => {
  const nextYr = lastYear + fixedYearVal;
  const percentSecondYear = (profitability / 100) * nextYr;
  const finalYr = percentSecondYear + nextYr;
  return finalYr;
};

// Calc years by number of years
const estimateByYears = (years) => {
  const contributions = 536.06;
  const profitability = 4.27;
  const fixedYearVal = 536.06 * 12; // 6.432,72
  const profitabilityVal =  (profitability / 100) * fixedYearVal;
  const fixedYearprofitability = fixedYearVal + profitabilityVal;
  const yearByYear = [fixedYearprofitability];

  for (let i = 1; i < years; i++) {
    let lastYr = yearByYear[yearByYear.length - 1];
    yearByYear.push(caclNextYear(lastYr, fixedYearVal, profitability));
  }
  
  return yearByYear;
};

// Call
const yearByYear = estimateByYears(5);
// yearByYear : [6707.397144, 13701.200146048799, 20993.63853628508, 28597.46404578445, 36525.97290453945
console.log('yearByYear', yearByYear);

Upvotes: 1

Related Questions