/* eslint-disable no-restricted-properties */ /** * @module Amount */ import * as Unit from "./unit"; export interface Amount { readonly value: number; readonly unit: Unit.Unit; readonly decimalCount: number; } export type Comparer = ( left: Amount, right: Amount ) => number; /** * Default comparer * @param left {Amount} The left-hand amount * @param right {Amount} The right-hand amount * @returns {number} Comparer value */ export const defaultComparer: Comparer = ( left: Amount, right: Amount ) => _comparison(left, right); /** * Creates an amount that represents the an exact/absolute value in the specified * unit. For example if you create an exact amount of 2 degrees Fahrenheit that * will represent -16.6666667 degrees Celsius. * @param value {number} The numeric value of the amount. * @param unit {Unit} The unit of the amount. * @param decimalCount {number | undefined} The decimalCount of the amount. * @returns {Amount} The created amount. */ export function create( value: number, unit: Unit.Unit, decimalCount: number | undefined = undefined ): Amount { if (decimalCount === undefined) { decimalCount = 0; const stringValue = value.toString(); const pointIndex = stringValue.indexOf("."); if (pointIndex >= 0) { decimalCount = stringValue.length - pointIndex - 1; } } return _factory(value, unit, decimalCount); } /** * Returns a string representation of an Amount. * @param amount {Amount} The amount. * @returns {string} String representation of the Amount. */ export function toString(amount: Amount): string { const unitname = Unit.buildDerivedSymbol(amount.unit); if (unitname.length > 0) { return amount.value.toString() + " " + unitname; } return amount.value.toString(); } /** * Negation unary operator. * @param amount {Amount} The amount. */ export function neg(amount: Amount): Amount { return create(-amount.value, amount.unit); } /** * Determines if an Amount is of a quantity. * @param quantity {Quantity} Quantity to check for. * @param amount {Amount} The amount to check. */ export function isQuantity(quantity: T, amount: Amount): boolean { // Amount does not store the quanitty but Unit does // return Unit.getQuantityType(amount.unit) === quantityType; return amount.unit.quantity === quantity; } /** * Adds two amounts together. * The two amounts amounts must have the same quantity. * The resulting amount will be of the same quantity as the two amounts. * The resulting amount will have it's decimal count set from the * most granular amount. * @param left The left-hand amount. * @param right The right-hand * @returns left + right */ export function plus( left: Amount, right: Amount ): Amount { const mostGranularAmount = getMostGranularAmount(left, right); return _factory( valueAs(mostGranularAmount.unit, left) + valueAs(mostGranularAmount.unit, right), mostGranularAmount.unit, mostGranularAmount.decimalCount ); } /** * Substracts two amounts from each other. * The two amounts amounts must have the same quantity. * The resulting amount will be of the same quantity as the two amounts. * The resulting amount will have it's decimal count set from the * most granular amount. * @param left The left-hand amount. * @param right The right-hand * @returns left + right */ export function minus( left: Amount, right: Amount ): Amount { const mostGranularAmount = getMostGranularAmount(left, right); return _factory( valueAs(mostGranularAmount.unit, left) - valueAs(mostGranularAmount.unit, right), mostGranularAmount.unit, mostGranularAmount.decimalCount ); } /** * Multiplies an amount with a number. * The resulting amount has the same unit and decimal count as the original amount. * @param left The amount to multiply * @param right The number to multiply with */ export function times( left: Amount, right: number | Amount ): Amount { if (typeof right === "number") { return _factory(left.value * right, left.unit, left.decimalCount); } else if (right.unit.quantity === "Dimensionless") { return _factory( left.value * valueAs(Unit.One, right), left.unit, left.decimalCount ); } else { throw new Error( `Cannot perform '*' operation with value of type '${right}'.` ); } } /** * Divides an amount with a number. * The resulting amount has the same unit and decimal count as the original amount. * @param left The amount to divide * @param right The number to divide by */ export function divide( left: Amount, right: number | Amount ): Amount { if (typeof right === "number") { return _factory(left.value / right, left.unit, left.decimalCount); } else if (right.unit.quantity === "Dimensionless") { return _factory( left.value / valueAs(Unit.One, right), left.unit, left.decimalCount ); } else { throw new Error( `Cannot perform '*' operation with value of type '${right}'.` ); } } /// Comparsion operators /** * Compares to amounts for equality * @param left {Amount} The left-hand Amount. * @param right {Amount} The right-hand Amount. * @returns {boolean} True if the amounts are equal, false otherwise. */ export function equals( left: Amount, right: Amount, comparer: Comparer = defaultComparer ): boolean { return compareAfterNullAndUndefinedCheck(left, right, true, comparer) === 0; } /** * Checks if one Amount is less than another. * @param left {Amount} The left-hand Amount. * @param right {Amount} The right-hand Amount. * @returns {boolean} True if the left-hand is less than the right-hand, false otherwise. */ export function lessThan( left: Amount, right: Amount, comparer: Comparer = defaultComparer ): boolean { return compareAfterNullAndUndefinedCheck(left, right, false, comparer) < 0; } /** * Checks if one Amount is greater than another. * @param left {Amount} The left-hand Amount. * @param right {Amount} The right-hand Amount. * @returns {boolean} True if the left-hand is less than the right-hand, false otherwise. */ export function greaterThan( left: Amount, right: Amount, comparer: Comparer = defaultComparer ): boolean { return compareAfterNullAndUndefinedCheck(left, right, false, comparer) > 0; } export const lessOrEqualTo = ( left: Amount, right: Amount, comparer: Comparer = defaultComparer ): boolean => compareAfterNullAndUndefinedCheck(left, right, false, comparer) <= 0; export const greaterOrEqualTo = ( left: Amount, right: Amount, comparer: Comparer = defaultComparer ): boolean => compareAfterNullAndUndefinedCheck(left, right, false, comparer) >= 0; export function clamp( minAmount: Amount, maxAmount: Amount, amount: Amount, comparer: Comparer = defaultComparer ): Amount { return min(maxAmount, max(minAmount, amount, comparer), comparer); } export function max( a1: Amount, a2: Amount, comparer: Comparer = defaultComparer ): Amount { if (!a2) { return a1; } if (!a1) { return a2; } return greaterThan(a1, a2, comparer) ? a1 : a2; } export function min( a1: Amount, a2: Amount, comparer: Comparer = defaultComparer ): Amount { if (!a2) { return a1; } if (!a1) { return a2; } return lessThan(a1, a2, comparer) ? a1 : a2; } /** * @param step Rounding step, for example 5.0 Celsius will round 23 to 20. * @param amount Amount to round. */ export function roundDown( step: Amount, amount: Amount ): Amount { const div = amount.value / step.value; return _factory( Math.floor(div) * step.value, amount.unit, step.decimalCount ); } /** * @param step Rounding step, for example 5.0 Celsius will round 23 to 25. * @param amount Amount to round. */ export function roundUp( step: Amount, amount: Amount ): Amount { const div = amount.value / step.value; return _factory( Math.ceil(div) * step.value, amount.unit, step.decimalCount ); } export function compareTo( left: Amount, right: Amount, comparer: Comparer = defaultComparer ): number { return compareAfterNullAndUndefinedCheck(left, right, true, comparer); } /** * Gets the absolute amount (equivalent of Math.Abs()) * @param amount The amount to get the aboslute amount from. */ export function abs(amount: Amount): Amount { return _factory(Math.abs(amount.value), amount.unit, amount.decimalCount); } /** * Gets the value of the amount as a number in the specified unit * @param toUnit The unit to get the amount in. * @param amount The amount to get the value from. */ export function valueAs( toUnit: Unit.Unit, amount: Amount ): number { if (Unit.equals(amount.unit, toUnit)) { return amount.value; } return Unit.convert(amount.value, amount.unit, toUnit); } /** * Gets the most granular unit * For example Millimeter is more granular than Meter so in that case * both units should be converted to millimeter before being compared and * we should use the decimal count of the amount which was specified in Millimeter * To find which is the most granular unit, we find the difference between 1 and 2 * in the units. The one with the highest difference is the most granular. * @param leftUnit * @param rightUnit * @returns The most granular unit. * @private */ export function getMostGranularUnit( leftUnit: Unit.Unit, rightUnit: Unit.Unit ): Unit.Unit { if (Unit.equals(leftUnit, rightUnit)) { return leftUnit; } const rightDelta = valueAs( leftUnit, minus(create(2, rightUnit), create(1, rightUnit)) ); if (rightDelta > 1) { return leftUnit; } else { return rightUnit; } } /////////////////////////////// /// BEGIN PRIVATE DECLARATIONS /////////////////////////////// function _factory( value: number, unit: Unit.Unit, decimalCount: number ): Amount { if (typeof value !== "number") { throw new Error("value must be a number."); } if (typeof unit !== "object") { throw new Error("unit must be an object."); } if (decimalCount !== undefined && typeof decimalCount !== "number") { throw new Error("decimalCount must be an undefined or a number."); } return { value: value, unit: unit, decimalCount: decimalCount, }; } function _comparison(left: Amount, right: Amount): number { // To handle decimals correctly when the units are different // we need to know which unit is the most granular. // Eg. when comparing 0:CubicMeterPerSecond with 36:CubicMeterPerHour, // both with 0 decimal places. const mostGranularUnit = getMostGranularUnit(left.unit, right.unit); const decimalCount = Math.max(left.decimalCount, right.decimalCount); const leftValue = valueAs(mostGranularUnit, left); const rightValue = valueAs(mostGranularUnit, right); const f = Math.round(leftValue * Math.pow(10, decimalCount)); const s = Math.round(rightValue * Math.pow(10, decimalCount)); if (f === s) { return 0; } if (f < s) { return -1; } else { return 1; } } /** * Gets the most granular amount * Takes into account both the unit and the decimalCount. * @param leftUnit * @param rightUnit * @private */ function getMostGranularAmount( left: Amount, right: Amount ): Amount { const rightSmallest = create(Math.pow(10, -right.decimalCount), right.unit); const rightSmallestInLeftUnit = valueAs(left.unit, rightSmallest); const leftSmallestInLeftUnit = Math.pow(10, -left.decimalCount); if (leftSmallestInLeftUnit < rightSmallestInLeftUnit) { return left; } return right; } function compareAfterNullAndUndefinedCheck( left: Amount, right: Amount, allowNullOrUndefined: boolean, comparer: Comparer ): number { if (!allowNullOrUndefined) { // We don't allow nulls for < and > because it would cause strange behavior, e.g. 1 < null would work which it shouldn't if (left === null || left === undefined) { throw new Error("ArgumentNull: left"); } if (right === null || right === undefined) { throw new Error("ArgumentNull: right"); } } else { // Handle nulls if ( (left === null && right === null) || (left === undefined && right === undefined) ) { return 0; } if (left === null || left === undefined) { return 1; } if (right === null || right === undefined) { return 2; } } return comparer(left, right); }