Last active
February 13, 2024 15:44
-
-
Save houssenedao/57352d57d089109b718d343d98858eb2 to your computer and use it in GitHub Desktop.
double-entry accounting
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
class Account { | |
// The name of the account | |
name: string; | |
// The type of the account (e.g. asset, liability, etc.) | |
type: string; | |
// The balance of the account | |
balance: number; | |
// Constructor that sets the name and type of the account | |
constructor(name: string, type: string) { | |
this.name = name; | |
this.type = type; | |
this.balance = 0; | |
} | |
// Method that debits the account by the specified amount | |
debit(amount: number) { | |
this.balance -= amount; | |
} | |
// Method that credits the account by the specified amount | |
credit(amount: number) { | |
this.balance += amount; | |
} | |
} | |
class Transaction { | |
// The date of the transaction | |
date: Date; | |
// The accounts involved in the transaction | |
accounts: Account[]; | |
// The amounts debited and credited for each account | |
amounts: number[]; | |
// Constructor that sets the date and accounts involved in the transaction | |
constructor(date: Date, accounts: Account[]) { | |
this.date = date; | |
this.accounts = accounts; | |
this.amounts = new Array(accounts.length).fill(0); | |
} | |
// Method that sets the amount debited or credited for a specific account | |
setAmount(account: Account, amount: number) { | |
const index = this.accounts.indexOf(account); | |
this.amounts[index] = amount; | |
} | |
// Method that records the transaction in the accounts | |
record() { | |
this.accounts.forEach((account, index) => { | |
if (this.amounts[index] < 0) { | |
account.debit(-this.amounts[index]); | |
} else { | |
account.credit(this.amounts[index]); | |
} | |
}); | |
} | |
} | |
// Create some accounts | |
const cash = new Account('Cash', 'asset'); | |
const accountsReceivable = new Account('Accounts Receivable', 'asset'); | |
const revenue = new Account('Revenue', 'income'); | |
// Create a transaction and set the amounts for each account | |
const transaction = new Transaction(new Date(), [cash, accountsReceivable, revenue]); | |
transaction.setAmount(cash, 100); | |
transaction.setAmount(accountsReceivable, -100); | |
transaction.setAmount(revenue, 100); | |
// Record the transaction in the accounts | |
transaction.record(); | |
// Print the balances of the accounts | |
console.log(cash.balance); // 100 | |
console.log(accountsReceivable.balance); // -100 | |
console.log(revenue.balance); // 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment