Skip to content

Instantly share code, notes, and snippets.

@Lootwig
Created November 14, 2022 22:51
Show Gist options
  • Save Lootwig/157f507a85dcb9321653834401e351d6 to your computer and use it in GitHub Desktop.
Save Lootwig/157f507a85dcb9321653834401e351d6 to your computer and use it in GitHub Desktop.
validator
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