Calculate multiple values ​in a loop - javascript

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 .
😢

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);

Related

JavaScript calculating deposit in bank for 3 years

Problem: You have deposited a sum into your bank account for 3 years. The bank has announced an interest of 5% per year. Each time the interest is calculated and added to your deposit. You have to calculate the amount in your deposit for each year. Also I must print the number with two numbers after the decimal point.
let i = gets();
let input = Number(i);
let firstYear = input + (input*(5/100));
let secondYear = firstYear + (firstYear*(5/100));
let thirdYear = secondYear + (secondYear*(5/100));
let printFirst = firstYear.toFixed(2);
let printSecond = secondYear.toFixed(2);
let printThird = thirdYear.toFixed(2);
print(printFirst);
print(printSecond);
print(printThird);
You can use a for loop like this
for(let i=0;i < 3;i++){
sum += sum * 0.05;
console.log(`${i} year: ${sum.toFixed(2)}`)
}

Function that doubles value by various rates

I'm trying to make a line chart like the New York Times Coronavirus Deaths by U.S. State and Country Over Time: Daily Tracker.
NYT has some clever lines in the chart showing the doubling rate, every day, every 2 days, every 3 days, every week, and so on.
I'm wondering how to write a function that returns an array of values that represent these lines given a start value of 10 and a maxX-value of 36 (total number of days as of today).
This is where I'm at right now, I'm afraid it does not calculate the values correctly but it might explain what I want to achieve.
How can I do this in a correct way? My math is too rusty for this.
var maxX = 36;
var start = 10;
function double(factor) {
var f = start;
var arr = [f];
for (var i = 1; i < maxX; i++) {
f = f + (f / factor)
arr.push(f)
}
return arr
}
var lines = [1, 2, 3, 7, 30].map(f => {
return {
days: f,
arr: double(f)
}
})
console.log(lines)
You first need to figure out what to multiply each daily value by, given a doubling rate. For example, with a doubling rate of every 2 days, you'd want each day count to be multiplied by 1.412 (square root of 2); after 1 day, it'd be 1.412x, after 2 days, it'd be 2x, after 4 days, it'd be 4x, etc.
For the general solution, the equation to solve is:
orig * (dayFactor ** daysToDouble) = 2 * orig
where orig is the original number of infections (here, 10), and dayFactor is the value you want to solve for, since that's the number the infections should be multiplied each day.
orig * (dayFactor ** daysToDouble) = 2 * orig
(dayFactor ** daysToDouble) = 2
dayFactor = 2 ** (1 / daysToDouble)
In the function, identify the dayFactor given the doubling rate, then multiply the count by that each day:
var maxX = 36;
var start = 10;
function double (daysToDouble) {
const dayFactor = 2 ** (1 / daysToDouble);
let currentInfected = start;
const arr = [currentInfected];
for (var i = 1; i < maxX; i++){
currentInfected *= dayFactor;
arr.push(currentInfected);
}
return arr;
}
var lines = [1,2,3,7,30].map(f => {
return {days: f, arr: double(f)}
});
console.log(lines[2]); // double every 3rd day

Compounding interest calculator in a loop in JavaScript

I am working on a calculator that calculates simple interest and compounding interest. All good, with the simple interest, but I can't seem to be able to solve the problem with the compounding interest, using a loop. I need a loop, because pushing the data into an array to use it in a chart later.
I have the formula from here: https://www.moneysmart.gov.au/managing-your-money/saving/compound-interest
I am using this as reference: https://www.bankrate.com/calculators/retirement/roi-calculator.aspx
The code is in work here: http://www.course0001.com/fiverr/iddqd
I have this so far(updated):
// Inputs from user:
// Initial deposit (starting balance)
// Number of years
// Interest
// Frequent Deposit amount
// Deposit and compound frequency (monthly, weekly, yearly)
// Calculations
var investedCapitalArray = [];
var simpleInterestArray = [];
var compoundInterestArray = [];
var compoundPrincipal = 0;
var years = [];
var accumulatedInvestment;
function calculate() {
years = [];
let interest = rateNumeric.getNumber() / 100; // annual interest rate
let additionalDeposit = additionalNumeric.getNumber(); // Regular deposit
let frequency = freqInput.value; // Frequency of regular deposit
let initialDeposit = initialNumeric.getNumber();
let taxRate = taxNumeric.getNumber();
// Invested captal amount first year
investedCapitalArray = [];
investedCapitalArray.push(initialDeposit + (frequency * additionalDeposit));
// simple interest first year
simpleInterestArray = [];
simpleInterestArray.push((investedCapitalArray[0] * ( (interest) / 100)) * (1 - taxRate));
// compund interest first year
compoundInterestArray = [];
let firstYearInvestment = investedCapitalArray[0]; // First deposit + regular deposits in first year
for (let i = 1 ; i < yearsInput.value ; i++) {
// Invested capital over the years (correct results)
investedCapitalArray.push( (investedCapitalArray[i-1]) +
(frequency * additionalDeposit) );
// simple interest over the years (correct results)
simpleInterestArray.push( simpleInterestArray[i-1] +
((firstYearInvestment +
((frequency) * additionalDeposit) * i ) * interest) );
// compound interest over the years (incorrect results)
compoundInterestArray.push( investedCapitalArray[i-1] *
Math.pow(1 + interest / 100, i) - initialDeposit);
years.push('Year' +i);
}
}
The issue is with the paranthesis you should use (investedCapitalArray[i - 1] + compoundInterestArray[i - 1]) * (1 + 0.07). Thanks
I think the problem is with unboxing the object. Try this:
compoundInterestArray.push( compoundInterestArray[i-1] + (parseInt(investedCapitalArray[i-1]) + parseInt(simpleInterestArray[i-1])) * ( rateNumberic.getNumber() / 100)) );
Thank you everyone for the inputs, after thoroughly researching the compounding interest topic, I wrote an algorithm that works perfectly. It's actually quite simple.
My algorithm is based on this explanation:
"What Is Compound Interest? Compound interest (or compounding interest) is interest calculated on the initial principal, which also includes all of the accumulated interest of previous periods of a deposit or loan."
Therefore it works like this in a loop:
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest));
Full code below.
for (let i = 1; i < yearsInput.value; i++) {
// Invested capital over the years (works fine)
investedCapital = (investedCapitalArray[i - 1]) +
(frequency * additionalDeposit);
investedCapitalArray.push(investedCapital);
// imple interest over the years (works fine)
simpleInterest = simpleInterestArray[i - 1] +
((firstYearInvestment + (frequency * additionalDeposit) * i) * interest);
simpleInterestArray.push(simpleInterest);
// compound interest over the years (correct results)
compoundInterest += (((simpleInterestArray[i - 1] + compoundInterest) * (interest)));
compoundInterestArray.push(compoundInterest);
}

Compounding interest monthly with a deposit

I want to compound interest on a weekly/fortnightly/monthly/annual basis.
I also want an option to have a deposit amount that can be added in.
I have already tried the standard formula of calculating the final amount accrued, as seen here:
(source: gstatic.com)
For example here is my method for calculating the interest compounding weekly:
function calculateWeekly(state: any) {
const { savings, deposit ,interest, timePeriodSelector, timePeriodLength } = state;
let numberOfYears = 0;
if (timePeriodSelector === "weekly") {
numberOfYears = timePeriodLength / weeksInAYear;
} else if (timePeriodSelector === "fortnightly") {
numberOfYears = (timePeriodLength / weeksInAYear) * 2;
} else if (timePeriodSelector === "monthly") {
numberOfYears = (timePeriodLength / weeksInAYear) * weeksInAMonth;
} else if (timePeriodSelector === "annually") {
numberOfYears = (timePeriodLength / weeksInAYear) * weeksInAYear;
}
const weeklyRate = interest / 100 / weeksInAYear;
const lengthOfCompunding = numberOfYears * weeksInAYear;
let startingFigure = parseInt(savings) + parseInt(deposit);
//total gets added on for every time cycle of week
let total =
(startingFigure * (Math.pow(1 + weeklyRate, lengthOfCompunding) - 1)) / weeklyRate;
return roundToTwoDP(total);
}
The issue with the above code is that the deposit gets added into the calculation every time the interest accrues. So a deposit of $10 weekly for 10 weeks will actually get added up to $100.
I attempted a method to accrue the interest using a loop for each week here:
// loops how many times to compound the interest
for(let i = numberOfYears - (1/weeksInAYear); i > 0; i-= (1/weeksInAYear)){
let interestGained = (total * (Math.pow((1 + weeklyRate), lengthOfCompunding))) - total;
total += interestGained + savings;
}
Thanks for any help!
This should do what you want:
const range = (min, max) => {
const size = 1 + max - min
return [...Array(size).keys()].map(n => n + min)
}
const weeksInAYear = 52
const addWeeklyInterest = interestRatePerWeek => (savings, _) => savings + savings * interestRatePerWeek
const calculateTotal = (savings, numberOfYears, interestRatePerWeek) => {
const numberOfWeeks = numberOfYears * weeksInAYear
return range(1, numberOfWeeks).reduce(addWeeklyInterest(interestRatePerWeek), savings)
}
console.log(calculateTotal(1000.00, 1, 0.02))
Output is 2800.328185448178. You might want to round that for display purposes, but also keep in mind that if accuracy is important, you can't use floating-point numbers.

Counter is not updated and it's value is replaced by the current value

I'm using 4 drop-down lists in an html form. The 2 drop downs, represent the starting and ending month of an activity and the other 2 represent the starting and the ending year of an activity. I'm allowing the user to enter a 3 year history and after completion, I prompt the user to go to the next section. To calculate the 3 year history, I take the difference between the start and ending month and I enter it each time in a counter (note that I am working with numbers and not with the Date object). The values are passed into my arrays, but the counter is not updated. It is just replaced by the new value in the array. Can anyone tell me where is the problem? Here is my code:
var arrMonthStarted = []; //It stores the month that activity started
var arrMonthEnded = []; //It stores the month that activity ended
var arrYearStarted = []; //It stores the year that activity started
var arrYearEnded = []; //It stores the year that activity ended
function validatedropdowns1(){
var monthStarted = document.getElementById('idMonthStarted').value;
var yearStarted = document.getElementById('idYearStarted').value;
var monthEnded = document.getElementById('idMonthEnded').value;
var yearEnded = document.getElementById('idYearEnded').value;
arrMonthStarted.push(monthStarted);
arrMonthEnded.push(monthEnded);
arrYearStarted.push(yearStarted);
arrYearEnded.push(yearEnded);
//Calculating the 3-year history
var count = 0;
if(yearStarted == yearEnded){
if(monthEnded < monthStarted){
var temp = monthEnded;
monthEnded = monthStarted;
monthStarted = temp;
}
var diffmonths = monthEnded - monthStarted;
count = count + diffmonths;
}
//Take the difference between the years.
var subYears = yearEnded - yearStarted;
//If 1, just take the difference on the first 2 lines of the calendar
if(subYears == 1){
var subLine1 = 12 - monthStarted;
var subLine2 = 12 - monthEnded;
var finalLine2 = 12 - subLine2;
var takeresult = subLine1 + finalLine2;
count = count + takeresult;
}
//Follow case 1, but also add 12 months
if(subYears == 2){
var subLine3 = 12 - monthStarted;
var subLine4 = 12 - monthEnded;
var finalLine3 = 12 - subLine4;
var takeresult11 = subLine3 + finalLine4;
var takeresult1 = 12 + takeresult11;
count = count + takeresult1l;
}
//add another 12 months (24 now) on step 1.
if(subYears == 3){
var subLine5 = 12 - monthStarted;
var subLine6 = 12 - monthEnded;
var finalLine5 = 12 - subLine6;
var takeresult22 = subLine5 + finalLine6;
var takeresult2 = 24 + takeresult22;
count = count + takeresult2;
}
var arrCount = []; // array to hold the count var
arrCount.push(count); // push count into arrCount
//print total months
for(var m = 0; m < arrCount.length; m++){
alert("The array now has" + "" + "" + count + "" + "months");
}
if(arrCount == 36){
alert("You have successfuly finished this section. Please go to the next section. Thank you.")
document.getElementById('btnAdd').disable = true;
}
if(arrMonthEnded[arrMonthEnded.length - 1] - arrMonthStarted[arrMonthSarted.length] > 1){
alert("There should not be a gap of more than a month in your 3 year activity. Fill in all the months and select from the list what you were doing each month. Thank you.")
}
}
Also, I was trying to test the gap between the end date and the next start date. For example if I enter 12 2011 as an end date and 03 2012 as the next start date, I would like to see if there is a gap of more than one month. I tried the code below, but it didn't work
if(arrMonthEnded[arrMonthEnded.length - 1] - arrMonthStarted[arrMonthSarted.length] > 1){
alert("There should not be a gap of more than a month in your 3 year activity. Fill in all the months and select from the list what you were doing each month. Thank you.")
}
Thank you in advance (KSFIDDLE http://jsfiddle.net/k4dNb/)
This loop is pointless, as the array will only ever have one item:
for(var m = 0; m < arrCount.length; m++){
Here you are comparing an array to a number, and eventhough that actually works because both will be converted to strings, and the string value of [36] is "36" which is the same as the string value of 36 which is "36", it's done in a confusing way:
if(arrCount == 36){
Typo, you wrote arrMonthSarted instead of arrMonthStarted:
if(arrMonthEnded[arrMonthEnded.length - 1] - arrMonthStarted[arrMonthSarted.length] > 1){
Also, arrMonthStarted[arrMonthStarted.length] will always return undefined, as you are trying to access an item beyond the last item of the array.

Categories