chore: strengthen backend eslint profile
This commit is contained in:
+11
-5
@@ -1,8 +1,10 @@
|
||||
export type Decimal = { value: bigint; scale: number };
|
||||
export type Decimal = { scale: number; value: bigint };
|
||||
|
||||
export function decimalFromString(value: string): Decimal {
|
||||
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value))
|
||||
// eslint-disable-next-line security/detect-unsafe-regex -- Anchored decimal grammar: the literal decimal point separates disjoint digit runs; backtracking is linear.
|
||||
if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value)) {
|
||||
throw new Error('Invalid decimal string');
|
||||
}
|
||||
const negative = value.startsWith('-');
|
||||
const [whole, fraction = ''] = (negative ? value.slice(1) : value).split('.');
|
||||
return {
|
||||
@@ -46,8 +48,12 @@ export function formatDecimal({ value, scale }: Decimal): string {
|
||||
.toString()
|
||||
.padStart(scale + 1, '0');
|
||||
const whole = digits.slice(0, -scale) || '0';
|
||||
const fraction = digits.slice(-scale).replace(/0+$/, '');
|
||||
return `${sign}${whole}${fraction ? `.${fraction}` : ''}`;
|
||||
const rawFraction = digits.slice(-scale);
|
||||
let fractionEnd = rawFraction.length;
|
||||
while (rawFraction.charAt(fractionEnd - 1) === '0') fractionEnd -= 1;
|
||||
const fraction = rawFraction.slice(0, fractionEnd);
|
||||
const fractionalPart = fraction ? '.' + fraction : '';
|
||||
return `${sign}${whole}${fractionalPart}`;
|
||||
}
|
||||
|
||||
// Round half away from zero; callers choose presentation precision explicitly.
|
||||
@@ -55,7 +61,7 @@ export function divide(left: Decimal, right: Decimal, scale: number): Decimal {
|
||||
if (right.value === 0n) throw new Error('Division by zero');
|
||||
const numerator = left.value * 10n ** BigInt(right.scale + scale);
|
||||
const denominator = right.value * 10n ** BigInt(left.scale);
|
||||
const sign = numerator < 0n !== denominator < 0n ? -1n : 1n;
|
||||
const sign = (numerator < 0n) !== (denominator < 0n) ? -1n : 1n;
|
||||
const n = numerator < 0n ? -numerator : numerator;
|
||||
const d = denominator < 0n ? -denominator : denominator;
|
||||
return { value: sign * ((n + d / 2n) / d), scale };
|
||||
|
||||
Reference in New Issue
Block a user