typia
Version:
Superfast runtime validators with only one line
1 lines • 3.69 kB
Source Map (JSON)
{"version":3,"file":"_decimal.mjs","names":[],"sources":["../../src/internal/_decimal.ts"],"sourcesContent":["export interface _IDecimal {\n coefficient: bigint;\n exponent: number;\n}\n\nexport interface _IDecimalRatio {\n numerator: bigint;\n denominator: bigint;\n}\n\nexport const _decimalDecompose = (value: number): _IDecimal | null => {\n if (Number.isFinite(value) === false) return null;\n const [mantissa = \"0\", exponentText = \"0\"] = value.toString().split(\"e\");\n const negative: boolean = mantissa.startsWith(\"-\");\n const unsigned: string = negative ? mantissa.slice(1) : mantissa;\n const point: number = unsigned.indexOf(\".\");\n const decimals: number = point === -1 ? 0 : unsigned.length - point - 1;\n const digits: bigint = BigInt(unsigned.replace(\".\", \"\"));\n return {\n coefficient: negative ? -digits : digits,\n exponent: Number(exponentText) - decimals,\n };\n};\n\nexport const _decimalDivide = (\n value: number,\n divisor: _IDecimal,\n): _IDecimalRatio | null => {\n const dividend: _IDecimal | null = _decimalDecompose(value);\n if (dividend === null || divisor.coefficient === BigInt(0)) return null;\n const exponent: number = dividend.exponent - divisor.exponent;\n return exponent >= 0\n ? {\n numerator: dividend.coefficient * _decimalPower(exponent),\n denominator: divisor.coefficient,\n }\n : {\n numerator: dividend.coefficient,\n denominator: divisor.coefficient * _decimalPower(-exponent),\n };\n};\n\nexport const _decimalIntegerStep = (value: number): _IDecimal | null => {\n const decimal: _IDecimal | null = _decimalDecompose(value);\n if (decimal === null || decimal.coefficient <= BigInt(0)) return null;\n if (decimal.exponent >= 0)\n return {\n coefficient: decimal.coefficient * _decimalPower(decimal.exponent),\n exponent: 0,\n };\n\n const denominator: bigint = _decimalPower(-decimal.exponent);\n return {\n coefficient:\n decimal.coefficient / _decimalGcd(decimal.coefficient, denominator),\n exponent: 0,\n };\n};\n\nexport const _decimalToNumber = (value: _IDecimal): number =>\n Number(`${value.coefficient}e${value.exponent}`);\n\nexport const _decimalPower = (exponent: number): bigint =>\n BigInt(10) ** BigIn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