UNPKG

rich-domain

Version:

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

52 lines 2.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Sum = 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 Adds two numbers (`valueA` and `valueB`) 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 to add. Can be a number or a value convertible to a number. * @param valueB The second value to add. 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 addition, 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. * * @example * ```typescript * Sum(10, 5); // Returns 15 * Sum(10, "3.5", 2); // Returns 13.50 * Sum(NaN, 5); // Returns 5 * Sum(10, NaN); // Returns 10 * Sum(NaN, NaN); // Returns 0 * ``` */ const Sum = (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); 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.Sum = Sum; exports.default = exports.Sum; //# sourceMappingURL=sum-number.util.js.map