All files / src/modules/implementations/numeric decimal.js

100% Statements 127/127
95.65% Branches 66/69
100% Functions 15/15
100% Lines 127/127

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 12872x 72x 813x 813x 413186x 980x 980x 413186x 413186x 813x 400861x 400861x 400861x 400861x 400861x 400857x 400861x 400861x 400861x 400861x 813x 613681x 613681x 613681x 613681x 1599x 1599x 1599x 545815x 613681x 813x 203105x 203105x 203105x 203105x 203105x 203105x 203105x 813x 145615x 145615x 145615x 813x 105x 105x 813x 7960x 7960x 7960x 7960x 7960x 813x 3284x 3284x 3284x 2x 2x 3281x 3281x 3281x 3281x 3284x 3284x 3284x 3284x 3284x 3284x 13x 13x 3284x 3284x 813x 813x 813x 364x 364x 813x 55968x 55968x 55968x 55968x 628x 628x 628x 55968x 55968x 813x 451x 451x 451x 451x 397x 397x 54x 17x 17x 17x 17x 17x 17x 17x 17x 451x 451x 451x 430x 430x 430x 451x 451x 813x 57490x 57490x 57490x 813x 813x 813x 813x 813x 813x 813x 813x 813x 813x 813x 813x 72x  
'use strict';
module.exports = () => {
    const POWERS_OF_TEN = [1n];
    function powerOfTen(exponent) {
        while (POWERS_OF_TEN.length <= exponent) {
            POWERS_OF_TEN.push(POWERS_OF_TEN[POWERS_OF_TEN.length - 1] * 10n);
        }
        return POWERS_OF_TEN[exponent];
    }
    function parseDecimal(value) {
        if (typeof value !== 'string')
            throw new TypeError('Decimal value must be a string');
        const match = /^([+-]?)(\d+)(?:\.(\d+))?$/u.exec(value);
        if (!match)
            throw new Error(`Invalid decimal value: ${JSON.stringify(value)}`);
        const integer = match[2];
        const fraction = match[3] || '';
        const sign = match[1] === '-' ? -1n : 1n;
        return normalizeDecimal({ coefficient: sign * BigInt(integer + fraction), scale: fraction.length });
    }
    function normalizeDecimal(decimal) {
        let { coefficient, scale } = decimal;
        if (coefficient === 0n)
            return { coefficient: 0n, scale: 0 };
        while (scale > 0 && coefficient % 10n === 0n) {
            coefficient /= 10n;
            scale--;
        }
        return { coefficient, scale };
    }
    function alignDecimals(left, right) {
        const scale = Math.max(left.scale, right.scale);
        return {
            left: left.coefficient * powerOfTen(scale - left.scale),
            right: right.coefficient * powerOfTen(scale - right.scale),
            scale,
        };
    }
    function addDecimals(left, right) {
        const aligned = alignDecimals(left, right);
        return normalizeDecimal({ coefficient: aligned.left + aligned.right, scale: aligned.scale });
    }
    function subtractDecimals(left, right) {
        return addDecimals(left, { coefficient: -right.coefficient, scale: right.scale });
    }
    function multiplyDecimals(left, right) {
        return normalizeDecimal({
            coefficient: left.coefficient * right.coefficient,
            scale: left.scale + right.scale,
        });
    }
    function divideRoundedDecimals(left, right, scale, tiesToEven) {
        if (right.coefficient === 0n)
            throw new RangeError('Cannot divide by zero');
        if (!Number.isInteger(scale) || scale < 0) {
            throw new RangeError('Decimal scale must be a non-negative integer');
        }
        const exponent = scale + right.scale - left.scale;
        const numerator = left.coefficient * powerOfTen(Math.max(exponent, 0));
        const denominator = right.coefficient * powerOfTen(Math.max(-exponent, 0));
        const negative = (numerator < 0n) !== (denominator < 0n);
        const absoluteNumerator = numerator < 0n ? -numerator : numerator;
        const absoluteDenominator = denominator < 0n ? -denominator : denominator;
        let coefficient = absoluteNumerator / absoluteDenominator;
        const remainderTwice = (absoluteNumerator % absoluteDenominator) * 2n;
        if (remainderTwice > absoluteDenominator ||
            (remainderTwice === absoluteDenominator && (!tiesToEven || coefficient % 2n !== 0n))) {
            coefficient += 1n;
        }
        return normalizeDecimal({ coefficient: negative ? -coefficient : coefficient, scale });
    }
    const divideDecimals = (left, right, scale) => divideRoundedDecimals(left, right, scale, false);
    const divideDecimalsHalfEven = (left, right, scale) => divideRoundedDecimals(left, right, scale, true);
    function negateDecimal(decimal) {
        return { coefficient: -decimal.coefficient, scale: decimal.scale };
    }
    function formatDecimal(decimal) {
        const normalized = normalizeDecimal(decimal);
        const negative = normalized.coefficient < 0n;
        let digits = (negative ? -normalized.coefficient : normalized.coefficient).toString();
        if (normalized.scale > 0) {
            digits = digits.padStart(normalized.scale + 1, '0');
            digits = `${digits.slice(0, -normalized.scale)}.${digits.slice(-normalized.scale)}`;
        }
        return negative ? `-${digits}` : digits;
    }
    function formatDecimalFixed(decimal, scale) {
        if (!Number.isInteger(scale) || scale < 0)
            throw new RangeError('Decimal scale must be a non-negative integer');
        let coefficient = decimal.coefficient;
        if (decimal.scale < scale) {
            coefficient *= powerOfTen(scale - decimal.scale);
        }
        else if (decimal.scale > scale) {
            const divisor = powerOfTen(decimal.scale - scale);
            const negative = coefficient < 0n;
            const absolute = negative ? -coefficient : coefficient;
            let rounded = absolute / divisor;
            if ((absolute % divisor) * 2n >= divisor)
                rounded += 1n;
            coefficient = negative ? -rounded : rounded;
        }
        const negative = coefficient < 0n;
        let digits = (negative ? -coefficient : coefficient).toString();
        if (scale > 0) {
            digits = digits.padStart(scale + 1, '0');
            digits = `${digits.slice(0, -scale)}.${digits.slice(-scale)}`;
        }
        return negative && coefficient !== 0n ? `-${digits}` : digits;
    }
    function compareDecimals(left, right) {
        const aligned = alignDecimals(left, right);
        return aligned.left < aligned.right ? -1 : Number(aligned.left > aligned.right);
    }
    return {
        addDecimals,
        compareDecimals,
        divideDecimals,
        divideDecimalsHalfEven,
        formatDecimal,
        formatDecimalFixed,
        multiplyDecimals,
        negateDecimal,
        parseDecimal,
        subtractDecimals,
    };
};