Calculating interest rates in Javascript: A guide to determining values using two separate rates

I am currently working on an earnings calculator function

EarningsCalculator.prototype.calculateEarning = function (interestRate, investmentAmount) {

    var earningHistory = {};
    var currentInvestment = investmentAmount;
    for (var year = 1; year <= 20; year++) {

            earnedAmount = currentInvestment * interestRate;

            currentInvestment = currentInvestment + earnedAmount;

        if (year % 5 === 0 || year === 1) {
            earningHistory[year] = currentInvestment;
        }
    }

    return earningHistory;
}

This function takes an initial "investment amount" and calculates the earnings based on a given interest rate. The calculation is done for multiple years using a loop, but I want to modify it slightly. I need the earnings at 1-year intervals for the first year and then at 5-year intervals from year 5 onwards.

So with an initial investment of $1000 and an interest rate of 10%, the output for 20 years would look like this:

Year1  = $1100
Year5  = $1610.51
Year10 = $2593.74246
Year15 = $4177.248169
Year20 = $6727.499949

Answer №1

If you want to calculate your earnings, you can use this formula.

function calculateEarnings(principal, rate, time) {
    return Math.pow(rate + 1, time) * principal;
}

var initialInvestment = 1000,
    annualInterestRate = 0.1,
    investmentPeriods = [1, 5, 10, 15, 20]
    
investmentPeriods.forEach(function (period) {
    console.log(period, calculateEarnings(initialInvestment, annualInterestRate, period));
});

Answer №2

To filter out only years divisible by 5 in your loop, you can use a modulus operation on the year values. Additionally, consider adding a condition to include the first year as well:

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

This implementation will output the correct values to your object when checked in the console.

An advantage of this approach is the flexibility to adjust the yearly interval by changing a variable rather than hardcoding specific values for different time periods.

JSFiddle: https://jsfiddle.net/kgill/zgmrtmhg/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bring in numerous documents utilizing a glob pattern

Currently, I am in the process of developing a modular React application. However, I have encountered an issue where I am unable to dynamically import the routes for my app. Consider the following file structure: app ├── app.js └── modules ...

Gain access to the "computed style" of elements in a directive

I recently created a directive for a loader element, but I am facing issues with undefined styles. Is there a way to access the "computed styles" of an element within the directive? export const ElementLoader = { componentUpdated(el, binding) { if ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...

Tips for incorporating local storage into Angular applications

After successfully creating a table using Angular, I decided to incorporate a local storage feature. Despite my efforts, I'm struggling with implementing gsklee/ngStorage and gregory/angular-local-storage libraries into my existing code. Could someon ...

Sharing a boolean state between two pages using Material UI components

One challenge I've been facing is passing a boolean useState value between two pages. I found a helpful solution on this Stack Overflow thread: How to call useState from another Page? The main goal here is to display a success alert on a separate pag ...

What is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Prevent further execution upon callback in an AJAX request by stopping the click event function

When the function myClick() is called within itself instead of myLoad() on the first click, it leads to double execution of myClick() on the second click. => This results in two consecutive executions of the click event for #myBtn with just one click. ...

Is it possible to include personalized validations in Formik's YupValidationSchema?

Is it possible to include custom validations in Formik's YupValidationSchema as shown below? YupValidationSchema = () => { return Yup.object({ Email: Yup.string() .max(256, "Length exceed 256 chars") ...

Is there a way to set up a loop for managing four separate drop-down lists?

While the code is functioning properly, I am determined to streamline it into a loop. Unfortunately, all my attempts thus far have been unsuccessful. The code displays four drop-down lists with different Id's, but they share the same class name (optio ...

When using addClass("test"), it throws an error message: TypeError: undefined is not a function

Upon examination in the console, I discovered the following: $(".myCssClass")[0].parentNode <li><span class="myCssClass">some text</span></li> I am attempting to add a CSS class to the parent span tag within the <li> element ...

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Issues arise with Highcharts Sankey chart failing to display all data when the font size for the series is increased

I am currently working with a simple sankey chart in Highcharts. Everything is functioning correctly with the sample data I have implemented, except for one issue - when I increase the font size of the data labels, not all the data is displayed. The info ...

JavaScript Challenge: Calculate the Number of Visible Characters in a Div

I have a div with text content (a string of length S) that is fixed in size but can be of any length. When the text exceeds a certain point (referred to as L), it gets truncated, and the portion beyond that limit becomes invisible. In other words, characte ...

how to choose the :after pseudo-element with jQuery

Below are the codes I have tried. When this popup appears, I want to be able to close the entire popbox using the close button. CSS code .bigdiv{ display:none; background-color:#efefef; box-shadow: 10px 10px 10px 100000px rgba(0, 0, 0, 0.4); ...

Fetching information from a data object using asyncData in Nuxt

Is there a method to retrieve object properties as keys from the asyncData() function? data() { return { bookmark_btn: { status: null, loading: false } } } I attempted to access data object properties in the following ...

The back button on an Angular JS application should display a confirmation dialog when pressed

I am currently working on an AngularJS mobile app that consists of various modules. One of my requirements is to access the device's back button within the application, and I also need a dialog with "OK" and "Cancel" options. Clicking on "OK" should ...

Is my rtk slice's initial state not being saved correctly in the store?

Currently diving into the world of RTK with typescript. I have created 2 slices - one using RTK query to fetch data (called apiSlice.ts) and another utilizing createSlice for handling synchronous state changes in my todo app (named snackbarSlice.ts). The ...

Understanding the getJSON MethodExplaining how

$.getJSON( main_url + "tasks/", { "task":8, "last":lastMsgID } I'm a bit confused about how this code functions. I'm looking for a way to retrieve messages from a shoutbox using a URL or some sort of method that the function here ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...