49 lines
1.1 KiB
TypeScript
49 lines
1.1 KiB
TypeScript
export class Money {
|
|
private constructor(
|
|
public readonly amount: number,
|
|
public readonly currency: string = 'USDT',
|
|
) {
|
|
if (amount < 0) {
|
|
throw new Error('金额不能为负数');
|
|
}
|
|
}
|
|
|
|
static USDT(amount: number): Money {
|
|
return new Money(amount, 'USDT');
|
|
}
|
|
|
|
static zero(): Money {
|
|
return new Money(0, 'USDT');
|
|
}
|
|
|
|
add(other: Money): Money {
|
|
if (this.currency !== other.currency) {
|
|
throw new Error('货币类型不匹配');
|
|
}
|
|
return new Money(this.amount + other.amount, this.currency);
|
|
}
|
|
|
|
subtract(other: Money): Money {
|
|
if (this.currency !== other.currency) {
|
|
throw new Error('货币类型不匹配');
|
|
}
|
|
return new Money(Math.max(0, 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;
|
|
}
|
|
|
|
isZero(): boolean {
|
|
return this.amount === 0;
|
|
}
|
|
|
|
isGreaterThan(other: Money): boolean {
|
|
return this.amount > other.amount;
|
|
}
|
|
}
|