Created
November 14, 2022 22:39
-
-
Save Lootwig/f9869741f80e9c2b79d247fc9433bd74 to your computer and use it in GitHub Desktop.
voucher-with-account
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; | |
} | |
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
My balance