UNPKG

rich-domain

Version:

This package provide utils file and interfaces to assistant build a complex application with domain driving design

53 lines 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Subtract = void 0; const ensure_number_1 = require("./ensure-number"); const is_nan_util_1 = require("./is-nan.util"); const normalize_number_util_1 = require("./normalize-number.util"); const to_decimal_number_util_1 = require("./to-decimal-number.util"); const to_long_number_util_1 = require("./to-long-number.util"); const to_precision_util_1 = require("./to-precision.util"); /** * @description Subtracts one number (`valueB`) from another (`valueA`) with optional precision adjustment. * Handles edge cases where inputs are not valid numbers by normalizing the values or returning defaults. * * @param valueA The first value (minuend). Can be a number or a value convertible to a number. * @param valueB The second value (subtrahend). Can be a number or a value convertible to a number. * @param precision The number of decimal places to apply to the result. Defaults to 5. * * @returns The result of the subtraction, normalized and adjusted to the specified precision. * Returns `0` if both inputs are `NaN`. If one of the inputs is invalid, the valid input is returned * (or negated if the second value is `NaN`). * * @example * ```typescript * Subtract(10, 2); // Returns 8 * Subtract(10, "3.5", 2); // Returns 6.50 * Subtract(NaN, 5); // Returns -5 * Subtract(10, NaN); // Returns 10 * Subtract(NaN, NaN); // Returns 0 * ``` */ const Subtract = (valueA, valueB, precision = 5) => { const isValueOneNumber = typeof valueA === 'number'; const isValueTwoNumber = typeof valueB === 'number'; const isBothNumber = isValueOneNumber && isValueTwoNumber; if (!isBothNumber) { const isNaNValueA = (0, is_nan_util_1.default)(valueA); const isNaNValueB = (0, is_nan_util_1.default)(valueB); const isBothNaN = isNaNValueA && isNaNValueB; if (isBothNaN) return 0; if (isNaNValueA) return (0, normalize_number_util_1.default)(valueB) * -1; if (isNaNValueB) return (0, normalize_number_util_1.default)(valueA); const result = (0, to_precision_util_1.default)((0, normalize_number_util_1.default)((0, to_decimal_number_util_1.default)((0, to_long_number_util_1.default)((0, normalize_number_util_1.default)(valueA)) - (0, to_long_number_util_1.default)((0, normalize_number_util_1.default)(valueB)))), precision); return (0, ensure_number_1.default)(result); } const result = (0, to_precision_util_1.default)((0, normalize_number_util_1.default)((0, to_decimal_number_util_1.default)((0, to_long_number_util_1.default)(valueA) - (0, to_long_number_util_1.default)(valueB))), precision); return (0, ensure_number_1.default)(result); }; exports.Subtract = Subtract; exports.default = exports.Subtract; //# sourceMappingURL=subtract-number.util.js.map