All files / libs/patterns/src/money account.ts

100% Statements 15/15
100% Branches 7/7
100% Functions 5/5
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                  15x         8x 8x       1x       7x           6x 5x     6x   6x       4x 1x     3x 1x     2x   2x      
import { CurrencyInterface } from "./currency";
import { MoneyInterface } from "./money";
 
export interface AccountInterface {
    getId(): number;
    getBalance(currency: CurrencyInterface): number;
    deposit(monye: MoneyInterface): number;
}
 
export class Account implements AccountInterface {
    protected id: number;
    protected balances: Map<CurrencyInterface, number>;
 
    public constructor(id: number) {
        this.id = id;
        this.balances = new Map<CurrencyInterface, number>();
    }
 
    public getId(): number {
        return this.id;
    }
 
    public getBalance(currency: CurrencyInterface): number {
        return this.balances.has(currency) && null != this.balances.get(currency)
            ? Number(this.balances.get(currency))
            : 0;
    }
 
    public deposit(money: MoneyInterface): number {
        if (!this.balances.has(money.getCurrency())) {
            this.balances.set(money.getCurrency(), 0);
        }
 
        this.balances.set(money.getCurrency(), Number(this.balances.get(money.getCurrency())) + money.getAmount());
 
        return Number(this.balances.get(money.getCurrency()));
    }
 
    public withdraw(money: MoneyInterface): number {
        if (!this.balances.has(money.getCurrency())) {
            throw new Error(`This account has no currency ${money.getCurrency().getStringRepresentation()}`);
        }
 
        if (Number(this.balances.get(money.getCurrency())) < money.getAmount()) {
            throw new Error("Balance is not enough for this withdraw");
        }
 
        this.balances.set(money.getCurrency(), Number(this.balances.get(money.getCurrency())) - money.getAmount());
 
        return Number(this.balances.get(money.getCurrency()));
    }
}