From 9cfce3af4c3e6e6dbe12259c536fd69fb2a6e3ff Mon Sep 17 00:00:00 2001 From: naveentehrpariya Date: Wed, 8 Jul 2026 17:22:39 +0530 Subject: [PATCH] fix: return the final exponent from output 'exponent' The output === 'exponent' early return fired before the bits auto-increment, rounding-overflow, and precision adjustments that can bump the exponent, so it could disagree with every other output mode: filesize(999999, {output: 'exponent'}) returned 1 while the string output is '1 MB' and object output reports exponent 2. Feeding the result back as a forced exponent then produced '1000 kB'. In bits mode the disagreement covers whole ranges (125000-999999 -> 1 vs 2). Move the early return after those adjustments so the reported exponent always matches the exponent used to render the value. --- src/filesize.js | 11 +++++++---- tests/unit/filesize.test.js | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/filesize.js b/src/filesize.js index 1977b11..12c54f4 100644 --- a/src/filesize.js +++ b/src/filesize.js @@ -126,10 +126,6 @@ export function filesize( e = calculatedE; const autoExponent = exponent === -1 || isNaN(exponent); - if (output === EXPONENT) { - return e; - } - const { result: valueResult, e: valueExponent } = calculateOptimizedValue( num, e, @@ -164,6 +160,13 @@ export function filesize( e = precisionResult.e; } + // Return the exponent only after every adjustment that other output + // modes apply (bits auto-increment, rounding overflow, precision), so + // it always matches the exponent reported by object output. + if (output === EXPONENT) { + return e; + } + u = resolveSymbol(actualStandard, bits, e, isDecimal); result[1] = u; diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 3e8ac6c..fa6a469 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -128,6 +128,26 @@ describe("filesize", () => { assert.strictEqual(typeof result, "number"); assert.strictEqual(result, 1); }); + + it("should match the object exponent when rounding overflows the unit", () => { + // 999999 renders as "1 MB", so the exponent is 2, not 1 + assert.strictEqual(filesize(999999, { output: "exponent" }), 2); + assert.strictEqual( + filesize(999999, { output: "exponent" }), + filesize(999999, { output: "object" }).exponent, + ); + // IEC: 1048575 renders as "1 MiB" + assert.strictEqual(filesize(1048575, { standard: "iec", output: "exponent" }), 2); + }); + + it("should match the object exponent when bits auto-increment the unit", () => { + // 125000 bytes = 1 Mbit, so the exponent is 2, not 1 + assert.strictEqual(filesize(125000, { bits: true, output: "exponent" }), 2); + assert.strictEqual( + filesize(125000, { bits: true, output: "exponent" }), + filesize(125000, { bits: true, output: "object" }).exponent, + ); + }); }); describe("Rounding", () => {