Created
November 14, 2022 22:51
-
-
Save Lootwig/157f507a85dcb9321653834401e351d6 to your computer and use it in GitHub Desktop.
validator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class Voucher { | |
description: string; | |
rows: VoucherRow[]; | |
constructor(description: string, rows: VoucherRow[]) { | |
this.description = description; | |
this.rows = rows; | |
} | |
get isBalanced(): boolean { | |
return this.rows.reduce((sum, row) => sum + row.credit + row.debit, 0) === 0; | |
} | |
addRow(row: VoucherRow) { | |
this.rows.push(row); | |
} | |
} | |
export class VoucherRow { | |
accountNumber: AccountNumber; | |
amount: number; | |
category: 'debit' | 'credit'; | |
constructor(accountNumber: AccountNumber, amount: number, category: 'debit' | 'credit') { | |
this.accountNumber = accountNumber; | |
this.amount = amount; | |
this.category = category; | |
} | |
static create(accountNumber: string, amount: number, category: 'debit' | 'credit'): VoucherRow | ParseError { | |
const parsed = AccountNumber.fromString(accountNumber); | |
if (parsed instanceof ParseError) { | |
return parsed; | |
} | |
return new VoucherRow(parsed, amount, category); | |
} | |
get debit(): number { | |
return this.category === 'debit' ? -this.amount : 0; | |
} | |
get credit(): number { | |
return this.category === 'credit' ? this.amount : 0; | |
} | |
} | |
export class AccountNumber { | |
number: number; | |
private constructor(number: number) { | |
this.number = number; | |
} | |
// usage: | |
// const accountNumber = AccountNumber.fromString('1900'); | |
// if (accountNumber instanceof ParseError) { | |
// console.log(accountNumber.message); | |
// } else { | |
// console.log(accountNumber.number); | |
// } | |
static fromString(str: string): AccountNumber | ParseError { | |
const number = parseInt(str); | |
if (isNaN(number) || number < 1900 || number > 1999) { | |
return new ParseError(`Invalid account number: ${str}`); | |
} | |
return new AccountNumber(number); | |
} | |
} | |
export class ParseError { | |
message: string; | |
constructor(message: string) { | |
this.message = message; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment