Using Modules

In this unit, you create a module that exposes the business logic related to a mortgage, and you build the application using Webpack.

Step 1: Create the Module

  1. Create a new file named mortgage.js in the js directory.

  2. Copy the calculateMonthlyPayment and calculateAmortization functions from main.js into mortgage.js.

  3. Add the export keyword in front of both functions to make them available as part of the module public API. mortgage.js should now look like this:

    export let calculateMonthlyPayment = (principal, years, rate) => {
        let monthlyRate = 0;
        if (rate) {
            monthlyRate = rate / 100 / 12;
        }
        let monthlyPayment = principal * monthlyRate / (1 - (Math.pow(1/(1 + monthlyRate),
                years * 12)));
        return {principal, years, rate, monthlyPayment, monthlyRate};
    };
        
    export let calculateAmortization = (principal, years, rate) => {
        let {monthlyRate, monthlyPayment} = calculateMonthlyPayment(principal, years, rate);
        let balance = principal;
        let amortization = [];
        for (let y=0; y<years; y++) {
            let interestY = 0;  //Interest payment for year y
            let principalY = 0; //Principal payment for year y
            for (let m=0; m<12; m++) {
                let interestM = balance * monthlyRate;       //Interest payment for month m
                let principalM = monthlyPayment - interestM; //Principal payment for month m
                interestY = interestY + interestM;
                principalY = principalY + principalM;
                balance = balance - principalM;
            }
            amortization.push({principalY, interestY, balance});
        }
        return {monthlyPayment, monthlyRate, amortization};
    };
    

Step 2: Use the Module

  1. In main.js, remove the calculateMonthlyPayment and calculateAmortization functions.

  2. Add the following import statement as the first line in main.js to import the mortgage module:

    import * as mortgage from './mortgage';
    
  3. In the calcBtn click event handler, modify the call to the calculateAmortization function as follows:

    let {monthlyPayment, monthlyRate, amortization} = 
        mortgage.calculateAmortization(principal, years, rate);
    

Step 3: Build and Run

  1. On the command line, type the following command to rebuild the application:

    npm run webpack
    
  2. Open a browser, access http://localhost:8080, and click the Calculate button.

Additional Resources

comments powered by Disqus