Skip to content

Instantly share code, notes, and snippets.

@devcsrj
Last active January 12, 2021 06:18
Show Gist options
  • Save devcsrj/f84fc04b2f02304e2e44ad3e737c9e94 to your computer and use it in GitHub Desktop.
Save devcsrj/f84fc04b2f02304e2e44ad3e737c9e94 to your computer and use it in GitHub Desktop.
Coding in Prose
const num: number = 11111111;
class AccountNumber {
private readonly value: number;
private constructor(value: number) {
this.value = value;
}
static from(value: number): AccountNumber {
if (lengthOf(value) != 10) 
throw new Error("Account number must be 10-digits");
return new AccountNumber(value);
}
}
const num: AccountNumber = AccountNumber.from(11111111);
const account: Account = ...;
account.withdraw(1000, "USD");
class Account {
withdraw(amount: double, currency: string) {
// deduct funds
}
}
const amount: Money = Money.of(1000, "USD");
const account: Account = …
account.withdraw(amount);
class Account {
withdraw(amount: Money) {
// deduct funds
}
}
class Account {
private _balance: Money;
withdraw(amount: Money) {
if (amount.isNegative())
throw new Error("Can't withdraw a negative amount");
_balance = _balance.minus(amount);
}
get balance(): Money {
return _balance;
}
}
class Account {
private balance: Money;
...
class Account {
private readonly credits: Credit[];
private readonly debits: Debit[];
withdraw(amount: Money) {
if (amount.isNegative())
throw new Error("Can't withdraw a negative amount");
debits.push(new Debit(amount));
}
get balance(point: Timepoint): Money {
// Add all credits up to point in time
const totalCredit = credits
.filter(c => c.before(point))
.map(c => c.amount())
.reduce((sum, current) => sum.plus(current), Money.ZERO);
// Add all debits up to point in time
const totalDebits = debits
.filter(d => d.before(point))
.map(d => d.amount())
.reduce((sum, current) => sum.plus(current), Money.ZERO);
// the difference IS the balance
return totalDebits.minus(totalCredits);
}
}
const account: Account = ...;
const twoDaysAgo = new Timepoint(2020, 12, 15); // Dec 15, 2020
const balanceTwoDaysAgo: Money = account.balance(twoDaysAgo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment