Skip to content

Commit

Permalink
Defensive coding for odd values scenarios
Browse files Browse the repository at this point in the history
  • Loading branch information
valadas committed Jul 9, 2024
1 parent f81ae56 commit 805239f
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/components/nvq-loan-calculator/nvq-loan-calculator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class NvqLoanCalculator {
}
}

private getValidatedNumber(target: HTMLInputElement, digits: number): number {
private getValidatedNumber(target: HTMLInputElement, digits: number, defaultValue: number = 0): number {
if (target.validity.valid) {
const value = parseFloat(target.value);
const roundedValue = this.roundTo(value, digits);
Expand All @@ -79,7 +79,7 @@ export class NvqLoanCalculator {
}

if (target.dataset.lastValidValue === undefined) {
target.dataset.lastValidValue = "0";
target.dataset.lastValidValue = defaultValue.toString();
}

target.value = this.roundTo(parseFloat(target.dataset.lastValidValue), digits).toString();
Expand Down Expand Up @@ -117,10 +117,13 @@ export class NvqLoanCalculator {
private calculatePayment() {
// Assuming monthly compounding.
const monthlyInterestRate = this.interestRate / 100 / 12;
if (this.amortizationYears === undefined){
return "";
}
const numberOfPayments = this.amortizationYears * 12;

if (monthlyInterestRate === 0) {
return (this.totalAmount - this.downPayment) / numberOfPayments;
return ((this.totalAmount - this.downPayment) / numberOfPayments).toFixed(2);
}

const monthlyPayment = (this.totalAmount - this.downPayment) * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments) / (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);
Expand Down Expand Up @@ -202,12 +205,12 @@ export class NvqLoanCalculator {
<input
type="number"
placeholder={this.amortizationPeriodLabel}
min={0}
min={1}
step={1}
required
value={this.amortizationYears}
onKeyDown={e => this.onlyAllowNumbers(e)}
onInput={e => this.amortizationYears = this.getValidatedNumber(e.target as HTMLInputElement, 0)}
onInput={e => this.amortizationYears = this.getValidatedNumber(e.target as HTMLInputElement, 0, 1)}
onBlur={e => this.displayErrorIfAny(e.target as HTMLInputElement)}
/>
<div class="error"></div>
Expand Down

0 comments on commit 805239f

Please sign in to comment.