@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.
92 lines • 2.97 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Money = void 0;
/* eslint-disable @typescript-eslint/no-unused-vars */
const Currency_1 = require("./Currency");
const big_js_1 = require("big.js");
const assertion_1 = require("../assertion/assertion");
class Money {
constructor(amount, currency) {
(0, assertion_1.assert)((0, assertion_1.notNull)(amount), 'Amount has to be defined');
(0, assertion_1.assert)((0, assertion_1.notNull)(currency), 'Currency has to be defined');
try {
this._amount = new big_js_1.Big(amount);
}
catch (error) {
throw new Error(`Invalid money amount: ${amount}`);
}
this._currency = typeof currency === 'string' ? Currency_1.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) {
(0, assertion_1.assert)(this.currency.code === money.currency.code, 'Currency mismatch');
}
}
exports.Money = Money;
//# sourceMappingURL=Money.js.map