UNPKG

typia

Version:

Superfast runtime validators with only one line

61 lines 2.55 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._decimalGcd = exports._decimalPower = exports._decimalToNumber = exports._decimalIntegerStep = exports._decimalDivide = exports._decimalDecompose = void 0; const _decimalDecompose = (value) => { if (Number.isFinite(value) === false) return null; const [mantissa = "0", exponentText = "0"] = value.toString().split("e"); const negative = mantissa.startsWith("-"); const unsigned = negative ? mantissa.slice(1) : mantissa; const point = unsigned.indexOf("."); const decimals = point === -1 ? 0 : unsigned.length - point - 1; const digits = BigInt(unsigned.replace(".", "")); return { coefficient: negative ? -digits : digits, exponent: Number(exponentText) - decimals, }; }; exports._decimalDecompose = _decimalDecompose; const _decimalDivide = (value, divisor) => { const dividend = (0, exports._decimalDecompose)(value); if (dividend === null || divisor.coefficient === BigInt(0)) return null; const exponent = dividend.exponent - divisor.exponent; return exponent >= 0 ? { numerator: dividend.coefficient * (0, exports._decimalPower)(exponent), denominator: divisor.coefficient, } : { numerator: dividend.coefficient, denominator: divisor.coefficient * (0, exports._decimalPower)(-exponent), }; }; exports._decimalDivide = _decimalDivide; const _decimalIntegerStep = (value) => { const decimal = (0, exports._decimalDecompose)(value); if (decimal === null || decimal.coefficient <= BigInt(0)) return null; if (decimal.exponent >= 0) return { coefficient: decimal.coefficient * (0, exports._decimalPower)(decimal.exponent), exponent: 0, }; const denominator = (0, exports._decimalPower)(-decimal.exponent); return { coefficient: decimal.coefficient / (0, exports._decimalGcd)(decimal.coefficient, denominator), exponent: 0, }; }; exports._decimalIntegerStep = _decimalIntegerStep; const _decimalToNumber = (value) => Number(`${value.coefficient}e${value.exponent}`); exports._decimalToNumber = _decimalToNumber; const _decimalPower = (exponent) => BigInt(10) ** BigInt(exponent); exports._decimalPower = _decimalPower; const _decimalGcd = (x, y) => { while (y !== BigInt(0)) [x, y] = [y, x % y]; return x < BigInt(0) ? -x : x; }; exports._decimalGcd = _decimalGcd; //# sourceMappingURL=_decimal.js.map