chore(amortization-calculator): address PR feedback

This commit is contained in:
copilot-swe-agent[bot] authored and Jacob Alford committed 2025-12-14 15:13:00 -07:00
1 parent 5ed43a0a2b
commit c133a76c49
5 files changed
+89 -91

No files matched your search

+1 -1
View File
@@ -1192,7 +1192,7 @@ tools:
label-total-interest: Total Interest
message-loan-amount-must-be-positive: Loan amount must be a positive value
message-loan-term-must-be-positive-integer: Loan term must be a positive integer
message-interest-rate-must-be-between-1-and-100: Interest rate must be a positive value between 1 and 100
message-interest-rate-must-be-between-1-and-100: Interest rate must be a positive value between 0 and 100
angle-converter:
title: Angle Units Converter
description: Convert values between angle units
@@ -120,7 +120,7 @@ test.describe('Tool - Amortization Calculator', () => {
await interestRateInput.fill('101');
await interestRateInput.blur();
await expect(page.locator('text=Interest rate must be a positive value between 1 and 100')).toBeVisible();
await expect(page.locator('text=Interest rate must be a positive value between 0 and 100')).toBeVisible();
});
test('Shows validation error for zero interest rate', async ({ page }) => {
@@ -130,7 +130,7 @@ test.describe('Tool - Amortization Calculator', () => {
await interestRateInput.fill('0');
await interestRateInput.blur();
await expect(page.locator('text=Interest rate must be a positive value between 1 and 100')).toBeVisible();
await expect(page.locator('text=Interest rate must be a positive value between 0 and 100')).toBeVisible();
});
test('Hides results when inputs are invalid', async ({ page }) => {
@@ -181,9 +181,9 @@ test.describe('Tool - Amortization Calculator', () => {
const lastMonthBalance = await scheduleTable.locator('tbody tr').nth(11).locator('td').nth(3).textContent();
// The values may contain country code in e2e tests
const firstBalanceValue = Number.parseFloat(firstBalance!.replace(/[A-z$,]/g, ''));
const sixthBalanceValue = Number.parseFloat(sixthBalance!.replace(/[A-z$,]/g, ''));
const lastBalanceValue = Number.parseFloat(lastMonthBalance!.replace(/[A-z$,]/g, ''));
const firstBalanceValue = Number.parseFloat(firstBalance!.replace(/[A-Za-z$,]/g, ''));
const sixthBalanceValue = Number.parseFloat(sixthBalance!.replace(/[A-Za-z$,]/g, ''));
const lastBalanceValue = Number.parseFloat(lastMonthBalance!.replace(/[A-Za-z$,]/g, ''));
expect(firstBalanceValue).toBeGreaterThan(sixthBalanceValue);
expect(sixthBalanceValue).toBeGreaterThan(lastBalanceValue);
@@ -2,8 +2,6 @@ import { beforeEach, describe, expect, it } from 'vitest';
import {
AmortizationCalculator,
type AmortizationParams,
type CachedPaymentResults,
type GetNthResult,
StandardAmortizationCalculator,
} from './amortization-calculator.service';
@@ -95,7 +93,7 @@ describe('StandardAmortizationCalculator', () => {
describe('getPayment', () => {
it('calculates correct payment for standard loan parameters', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005, // 0.5% monthly (6% annual)
numberOfPayments: 360, // 30 years
};
@@ -111,7 +109,7 @@ describe('StandardAmortizationCalculator', () => {
it('calculates correct payment for short-term loan', () => {
const params: AmortizationParams = {
principle: 10000,
principal: 10000,
periodInterestRate: 0.01, // 1% monthly
numberOfPayments: 12,
};
@@ -124,21 +122,21 @@ describe('StandardAmortizationCalculator', () => {
it('calculates correct payment with zero interest rate', () => {
const params: AmortizationParams = {
principle: 12000,
principal: 12000,
periodInterestRate: 0,
numberOfPayments: 12,
};
const result = calculator.getPayment(params);
// With 0% interest, payment should be principle / numberOfPayments
// With 0% interest, payment should be principal / numberOfPayments
expect(result.payment).toBe(1000);
expect(result.totalPayments).toBe(12000);
});
it('caches payment calculations', () => {
const params: AmortizationParams = {
principle: 50000,
principal: 50000,
periodInterestRate: 0.004,
numberOfPayments: 180,
};
@@ -153,13 +151,13 @@ describe('StandardAmortizationCalculator', () => {
it('calculates different payments for different parameters', () => {
const params1: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 360,
};
const params2: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.004,
numberOfPayments: 360,
};
@@ -175,7 +173,7 @@ describe('StandardAmortizationCalculator', () => {
describe('getNth', () => {
it('calculates correct values for first payment', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 360,
};
@@ -187,16 +185,16 @@ describe('StandardAmortizationCalculator', () => {
// First payment: more interest, less principal in standard amortization
expect(result.interestPayment).toBeCloseTo(500, 2); // 100000 * 0.005
expect(result.principlePayment).toBeCloseTo(99.55, 2); // 599.55 - 500
expect(result.principalPayment).toBeCloseTo(99.55, 2); // 599.55 - 500
expect(result.remainingBalance).toBeCloseTo(99900.45, 2); // 100000 - 99.55
// Payment should equal principal + interest
expect(result.principlePayment + result.interestPayment).toBeCloseTo(result.payment, 2);
expect(result.principalPayment + result.interestPayment).toBeCloseTo(result.payment, 2);
});
it('calculates correct values for middle payment', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 360,
};
@@ -205,13 +203,13 @@ describe('StandardAmortizationCalculator', () => {
expect(result.paymentIndex).toBe(180);
expect(result.remainingBalance).toBeGreaterThan(0);
expect(result.remainingBalance).toBeLessThan(params.principle);
expect(result.principlePayment + result.interestPayment).toBeCloseTo(result.payment, 2);
expect(result.remainingBalance).toBeLessThan(params.principal);
expect(result.principalPayment + result.interestPayment).toBeCloseTo(result.payment, 2);
});
it('calculates correct values for final payment', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 360,
};
@@ -221,12 +219,12 @@ describe('StandardAmortizationCalculator', () => {
expect(result.paymentIndex).toBe(360);
// Last payment should have remaining balance close to 0
expect(result.remainingBalance).toBeCloseTo(0, 0);
expect(result.principlePayment + result.interestPayment).toBeCloseTo(result.payment, 2);
expect(result.principalPayment + result.interestPayment).toBeCloseTo(result.payment, 2);
});
it('shows increasing principal payment over time for standard amortization', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 360,
};
@@ -236,13 +234,13 @@ describe('StandardAmortizationCalculator', () => {
const payment360 = calculator.getNth(params, 360);
// In standard amortization, principal payment increases as balance decreases
expect(payment1.principlePayment).toBeLessThan(payment180.principlePayment);
expect(payment180.principlePayment).toBeLessThan(payment360.principlePayment);
expect(payment1.principalPayment).toBeLessThan(payment180.principalPayment);
expect(payment180.principalPayment).toBeLessThan(payment360.principalPayment);
});
it('shows decreasing interest payment over time', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 360,
};
@@ -258,7 +256,7 @@ describe('StandardAmortizationCalculator', () => {
it('handles zero interest rate correctly', () => {
const params: AmortizationParams = {
principle: 12000,
principal: 12000,
periodInterestRate: 0,
numberOfPayments: 12,
};
@@ -267,14 +265,14 @@ describe('StandardAmortizationCalculator', () => {
expect(result.payment).toBe(1000);
expect(result.interestPayment).toBe(0);
expect(result.principlePayment).toBeGreaterThan(0);
expect(result.principalPayment).toBeGreaterThan(0);
});
});
describe('getAmortizationSchedule', () => {
it('generates complete amortization schedule with month and year rows', () => {
const params: AmortizationParams = {
principle: 10000,
principal: 10000,
periodInterestRate: 0.01,
numberOfPayments: 12,
};
@@ -293,7 +291,7 @@ describe('StandardAmortizationCalculator', () => {
it('ensures each payment has consistent structure', () => {
const params: AmortizationParams = {
principle: 50000,
principal: 50000,
periodInterestRate: 0.004,
numberOfPayments: 60,
};
@@ -312,20 +310,20 @@ describe('StandardAmortizationCalculator', () => {
monthRows.forEach((payment, index) => {
expect(payment).toHaveProperty('paymentIndex');
expect(payment).toHaveProperty('payment');
expect(payment).toHaveProperty('principlePayment');
expect(payment).toHaveProperty('principalPayment');
expect(payment).toHaveProperty('interestPayment');
expect(payment).toHaveProperty('remainingBalance');
expect(payment).toHaveProperty('totalPayments');
expect(payment).toHaveProperty('type');
expect(payment.paymentIndex).toBe(index + 1);
expect(payment.principlePayment + payment.interestPayment).toBeCloseTo(payment.payment, 2);
expect(payment.principalPayment + payment.interestPayment).toBeCloseTo(payment.payment, 2);
});
});
it('shows decreasing remaining balance over time', () => {
const params: AmortizationParams = {
principle: 20000,
principal: 20000,
periodInterestRate: 0.005,
numberOfPayments: 24,
};
@@ -342,7 +340,7 @@ describe('StandardAmortizationCalculator', () => {
it('ends with near-zero remaining balance', () => {
const params: AmortizationParams = {
principle: 15000,
principal: 15000,
periodInterestRate: 0.0075,
numberOfPayments: 36,
};
@@ -356,7 +354,7 @@ describe('StandardAmortizationCalculator', () => {
it('handles single payment loan', () => {
const params: AmortizationParams = {
principle: 1000,
principal: 1000,
periodInterestRate: 0.05,
numberOfPayments: 1,
};
@@ -372,7 +370,7 @@ describe('StandardAmortizationCalculator', () => {
it('maintains consistent payment amount throughout schedule', () => {
const params: AmortizationParams = {
principle: 25000,
principal: 25000,
periodInterestRate: 0.006,
numberOfPayments: 48,
};
@@ -388,7 +386,7 @@ describe('StandardAmortizationCalculator', () => {
it('includes year summary rows after every 12 months', () => {
const params: AmortizationParams = {
principle: 100000,
principal: 100000,
periodInterestRate: 0.005,
numberOfPayments: 24,
};
@@ -403,7 +401,7 @@ describe('StandardAmortizationCalculator', () => {
it('year summary rows contain cumulative totals', () => {
const params: AmortizationParams = {
principle: 10000,
principal: 10000,
periodInterestRate: 0.01,
numberOfPayments: 12,
};
@@ -413,10 +411,10 @@ describe('StandardAmortizationCalculator', () => {
const yearRows = schedule.filter(row => row.type === 'year');
// Calculate cumulative totals for the year
const totalPrinciple = monthRows.reduce((sum, row) => sum + row.principlePayment, 0);
const totalPrincipal = monthRows.reduce((sum, row) => sum + row.principalPayment, 0);
const totalInterest = monthRows.reduce((sum, row) => sum + row.interestPayment, 0);
expect(yearRows[0].principlePayment).toBeCloseTo(totalPrinciple, 2);
expect(yearRows[0].principalPayment).toBeCloseTo(totalPrincipal, 2);
expect(yearRows[0].interestPayment).toBeCloseTo(totalInterest, 2);
});
});
@@ -424,19 +422,19 @@ describe('StandardAmortizationCalculator', () => {
describe('edge cases', () => {
it('handles very small loan amounts', () => {
const params: AmortizationParams = {
principle: 100,
principal: 100,
periodInterestRate: 0.01,
numberOfPayments: 12,
};
const result = calculator.getPayment(params);
expect(result.payment).toBeGreaterThan(0);
expect(result.totalPayments).toBeGreaterThan(params.principle);
expect(result.totalPayments).toBeGreaterThan(params.principal);
});
it('handles very large loan amounts', () => {
const params: AmortizationParams = {
principle: 10000000,
principal: 10000000,
periodInterestRate: 0.003,
numberOfPayments: 360,
};
@@ -448,18 +446,18 @@ describe('StandardAmortizationCalculator', () => {
it('handles very low interest rates', () => {
const params: AmortizationParams = {
principle: 50000,
principal: 50000,
periodInterestRate: 0.0001,
numberOfPayments: 60,
};
const result = calculator.getPayment(params);
expect(result.payment).toBeGreaterThan(params.principle / params.numberOfPayments);
expect(result.payment).toBeGreaterThan(params.principal / params.numberOfPayments);
});
it('handles short loan terms', () => {
const params: AmortizationParams = {
principle: 5000,
principal: 5000,
periodInterestRate: 0.02,
numberOfPayments: 3,
};
@@ -473,7 +471,7 @@ describe('StandardAmortizationCalculator', () => {
it('handles long loan terms', () => {
const params: AmortizationParams = {
principle: 200000,
principal: 200000,
periodInterestRate: 0.004,
numberOfPayments: 480, // 40 years
};
@@ -1,26 +1,26 @@
export interface AmortizationParams {
readonly principle: number;
readonly periodInterestRate: number;
readonly numberOfPayments: number;
readonly principal: number
readonly periodInterestRate: number
readonly numberOfPayments: number
}
export interface CachedPaymentResults {
readonly payment: number;
readonly totalPayments: number;
readonly payment: number
readonly totalPayments: number
}
export interface GetNthResult extends CachedPaymentResults {
readonly paymentIndex: number;
readonly principlePayment: number;
readonly interestPayment: number;
readonly remainingBalance: number;
readonly paymentIndex: number
readonly principalPayment: number
readonly interestPayment: number
readonly remainingBalance: number
}
export interface AmortizationScheduleItem extends GetNthResult {
readonly type: 'month' | 'year';
readonly type: 'month' | 'year'
}
type AmortizationPaymentCacheKey = `principle:${number};interest-rate:${number};number-of-payments:${number}`;
type AmortizationPaymentCacheKey = `principal:${number};interest-rate:${number};number-of-payments:${number}`;
export abstract class AmortizationCalculator {
public static validateLoanAmount(str: string): boolean {
@@ -39,13 +39,13 @@ export abstract class AmortizationCalculator {
public *getAmortizationSchedule(params: AmortizationParams): Generator<AmortizationScheduleItem> {
let period = 0;
let periodTotalPrinciple = 0;
let periodTotalPrincipal = 0;
let periodTotalInterest = 0;
while (period < params.numberOfPayments) {
const periodResults = this.getNth(params, ++period);
periodTotalPrinciple += periodResults.principlePayment;
periodTotalPrincipal += periodResults.principalPayment;
periodTotalInterest += periodResults.interestPayment;
yield {
@@ -58,12 +58,12 @@ export abstract class AmortizationCalculator {
yield {
...periodResults,
paymentIndex: period / 12,
principlePayment: periodTotalPrinciple,
principalPayment: periodTotalPrincipal,
interestPayment: periodTotalInterest,
type: 'year',
};
periodTotalPrinciple = 0;
periodTotalPrincipal = 0;
periodTotalInterest = 0;
}
}
@@ -85,23 +85,23 @@ export abstract class AmortizationCalculator {
this.paymentCache.set(cacheKey, paymentResult);
return paymentResult;
} else {
return cache;
}
return cache;
}
/** Private Methods */
private paymentCache: Map<AmortizationPaymentCacheKey, CachedPaymentResults> = new Map();
private calculatePayment({ principle, periodInterestRate, numberOfPayments }: AmortizationParams): number {
private calculatePayment({ principal, periodInterestRate, numberOfPayments }: AmortizationParams): number {
if (periodInterestRate === 0) {
return principle / numberOfPayments;
return principal / numberOfPayments;
}
const numerator = periodInterestRate * (1 + periodInterestRate) ** numberOfPayments;
const denominator = (1 + periodInterestRate) ** numberOfPayments - 1;
return principle * (numerator / denominator);
return principal * (numerator / denominator);
}
private calculateTotalPayments({ numberOfPayments }: AmortizationParams, payment: number): number {
@@ -109,11 +109,11 @@ export abstract class AmortizationCalculator {
}
private getCacheString({
principle,
principal,
periodInterestRate,
numberOfPayments,
}: AmortizationParams): AmortizationPaymentCacheKey {
return `principle:${principle};interest-rate:${periodInterestRate};number-of-payments:${numberOfPayments}`;
return `principal:${principal};interest-rate:${periodInterestRate};number-of-payments:${numberOfPayments}`;
}
private static validatePositiveInteger(str: string): boolean {
@@ -144,39 +144,39 @@ export class StandardAmortizationCalculator extends AmortizationCalculator {
getNth(params: AmortizationParams, paymentIndex: number): GetNthResult {
const { payment, totalPayments } = this.getPayment(params);
const { principle, periodInterestRate, numberOfPayments } = params;
const { principal, periodInterestRate, numberOfPayments } = params;
if (periodInterestRate === 0) {
const principlePayment = principle / numberOfPayments;
const remainingBalance = principle - principlePayment * paymentIndex;
const principalPayment = principal / numberOfPayments;
const remainingBalance = principal - principalPayment * paymentIndex;
return {
payment,
totalPayments,
remainingBalance: Math.max(0, remainingBalance),
interestPayment: 0,
principlePayment,
principalPayment,
paymentIndex,
};
}
const r = 1 + periodInterestRate;
const balanceBeforePayment =
principle * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate);
const balanceBeforePayment
= principal * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate);
const interestPayment = balanceBeforePayment * periodInterestRate;
const principlePayment = payment - interestPayment;
const principalPayment = payment - interestPayment;
const remainingBalance = balanceBeforePayment - principlePayment;
const remainingBalance = balanceBeforePayment - principalPayment;
return {
payment,
totalPayments,
remainingBalance,
interestPayment,
principlePayment,
principalPayment,
paymentIndex,
};
}
@@ -12,7 +12,7 @@ const amortizationCalculator = ref(new StandardAmortizationCalculator());
const currencyDisplayNames = computed(() => new Intl.DisplayNames(locale.value, { type: 'currency' }));
const supportedCurrencies = ref(
Intl.supportedValuesOf('currency').map((value) => ({
Intl.supportedValuesOf('currency').map(value => ({
value,
label: currencyDisplayNames.value.of(value),
})),
@@ -78,17 +78,19 @@ const allValid = computed(
const payment = computed(() =>
amortizationCalculator.value.getPayment({
principle: parsedLoanAmount.value,
principal: parsedLoanAmount.value,
periodInterestRate: parsedInterestRate.value / 1200,
numberOfPayments: parsedLoanMonths.value,
}),
);
const amortizationSchedule = computed(() => {
// Re-initialize generator when currency changes
// Force re-render on currency changes
// i.e. redeclare generator
// eslint-disable-next-line no-unused-expressions
selectedCurrency.value;
return amortizationCalculator.value.getAmortizationSchedule({
principle: parsedLoanAmount.value,
principal: parsedLoanAmount.value,
periodInterestRate: parsedInterestRate.value / 1200,
numberOfPayments: parsedLoanMonths.value,
});
@@ -109,7 +111,7 @@ function formatCurrency(num: number): string {
<c-card :title="t('tools.amortization-calculator.texts.title-loan-parameters')" mb-5>
<c-input-text
v-model:value="loanAmount"
:placeholder="'e.g. 200000'"
placeholder="e.g. 200000"
:label="t('tools.amortization-calculator.texts.label-loan-amount')"
raw-text
mb-5
@@ -118,7 +120,7 @@ function formatCurrency(num: number): string {
<c-input-text
v-model:value="loanMonths"
:placeholder="'e.g. 360'"
placeholder="e.g. 360"
:label="t('tools.amortization-calculator.texts.label-loan-term')"
raw-text
mb-5
@@ -127,7 +129,7 @@ function formatCurrency(num: number): string {
<c-input-text
v-model:value="interestRate"
:placeholder="'e.g. 6.0'"
placeholder="e.g. 6.0"
:label="t('tools.amortization-calculator.texts.label-interest-rate')"
raw-text
mb-5
@@ -168,15 +170,15 @@ function formatCurrency(num: number): string {
<tbody>
<tr v-for="period in amortizationSchedule" :key="period.type + period.paymentIndex">
<template v-if="period.type === 'month'">
<td v-if="period.type === 'month'">{{ period.paymentIndex }}</td>
<td>{{ period.paymentIndex }}</td>
<td>{{ formatCurrency(period.interestPayment) }}</td>
<td>{{ formatCurrency(period.principlePayment) }}</td>
<td>{{ formatCurrency(period.principalPayment) }}</td>
<td>{{ formatCurrency(period.remainingBalance) }}</td>
</template>
<template v-else>
<th>{{ t('tools.amortization-calculator.texts.label-end-of-year', { year: period.paymentIndex }) }}</th>
<th>{{ formatCurrency(period.interestPayment) }}</th>
<th>{{ formatCurrency(period.principlePayment) }}</th>
<th>{{ formatCurrency(period.principalPayment) }}</th>
<th>{{ formatCurrency(period.remainingBalance) }}</th>
</template>
</tr>
@@ -184,5 +186,3 @@ function formatCurrency(num: number): string {
</n-table>
</div>
</template>
<style lang="less" scoped></style>