@citrineos/base
Version:
The base module for OCPP v2.0.1 including all interfaces. This module is not intended to be used directly, but rather as a dependency for other modules.
88 lines • 2.74 kB
JavaScript
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Currency } from './Currency';
import { Big } from 'big.js';
import { assert, notNull } from '../assertion/assertion';
export class Money {
constructor(amount, currency) {
assert(notNull(amount), 'Amount has to be defined');
assert(notNull(currency), 'Currency has to be defined');
try {
this._amount = new Big(amount);
}
catch (error) {
throw new Error(`Invalid money amount: ${amount}`);
}
this._currency = typeof currency === 'string' ? Currency.of(currency) : currency;
}
get amount() {
return this._amount;
}
get currency() {
return this._currency;
}
static of(amount, currency) {
return new Money(amount, currency);
}
static USD(amount) {
return new Money(amount, 'USD');
}
toNumber() {
return this._amount.toNumber();
}
/**
* Rounds the amount down to match the currency's defined scale.
* This method could be used when converting an amount to its final monetary value.
*
* @returns {Money} A new Money instance with the amount rounded down to the currency's scale.
*/
roundToCurrencyScale() {
const newAmount = this._amount.round(this.currency.scale, 0);
return this.withAmount(newAmount);
}
multiply(multiplier) {
return this.withAmount(this.amount.times(multiplier));
}
add(money) {
this.requireSameCurrency(money);
return this.withAmount(this.amount.plus(money.amount));
}
subtract(money) {
this.requireSameCurrency(money);
return this.withAmount(this.amount.minus(money.amount));
}
equals(money) {
return this._currency === money._currency && this.amount.eq(money.amount);
}
greaterThan(money) {
this.requireSameCurrency(money);
return this.amount.gt(money.amount);
}
greaterThanOrEqual(money) {
this.requireSameCurrency(money);
return this.amount.gte(money.amount);
}
lessThan(money) {
this.requireSameCurrency(money);
return this.amount.lt(money.amount);
}
lessThanOrEqual(money) {
this.requireSameCurrency(money);
return this.amount.lte(money.amount);
}
isZero() {
return this.amount.eq(0);
}
isPositive() {
return this.amount.gt(0);
}
isNegative() {
return this.amount.lt(0);
}
withAmount(amount) {
return new Money(amount, this._currency);
}
requireSameCurrency(money) {
assert(this.currency.code === money.currency.code, 'Currency mismatch');
}
}
//# sourceMappingURL=Money.js.map