60 lines
1.5 KiB
TypeScript
60 lines
1.5 KiB
TypeScript
export class Money {
|
|
private constructor(
|
|
public readonly amount: number,
|
|
public readonly currency: string = 'USDT',
|
|
) {
|
|
if (amount < 0) {
|
|
throw new Error('金额不能为负数');
|
|
}
|
|
}
|
|
|
|
static create(amount: number, currency: string = 'USDT'): Money {
|
|
return new Money(amount, currency);
|
|
}
|
|
|
|
static zero(currency: string = 'USDT'): Money {
|
|
return new Money(0, currency);
|
|
}
|
|
|
|
add(other: Money): Money {
|
|
this.ensureSameCurrency(other);
|
|
return new Money(this.amount + other.amount, this.currency);
|
|
}
|
|
|
|
subtract(other: Money): Money {
|
|
this.ensureSameCurrency(other);
|
|
if (this.amount < other.amount) {
|
|
throw new Error('余额不足');
|
|
}
|
|
return new Money(this.amount - other.amount, this.currency);
|
|
}
|
|
|
|
multiply(factor: number): Money {
|
|
return new Money(this.amount * factor, this.currency);
|
|
}
|
|
|
|
equals(other: Money): boolean {
|
|
return this.amount === other.amount && this.currency === other.currency;
|
|
}
|
|
|
|
isGreaterThan(other: Money): boolean {
|
|
this.ensureSameCurrency(other);
|
|
return this.amount > other.amount;
|
|
}
|
|
|
|
isLessThan(other: Money): boolean {
|
|
this.ensureSameCurrency(other);
|
|
return this.amount < other.amount;
|
|
}
|
|
|
|
private ensureSameCurrency(other: Money): void {
|
|
if (this.currency !== other.currency) {
|
|
throw new Error(`货币类型不匹配: ${this.currency} vs ${other.currency}`);
|
|
}
|
|
}
|
|
|
|
toString(): string {
|
|
return `${this.amount} ${this.currency}`;
|
|
}
|
|
}
|