From e0ac63cb9d8cc361171bf9f7cb176f5f3d88a980 Mon Sep 17 00:00:00 2001 From: Alexander Kireev Date: Fri, 3 Jul 2026 08:53:05 +0700 Subject: [PATCH] fix(helpers): clamp negative forced exponent to 0 calculateExponent only clamps e > 8, but any exponent below -1 (the documented auto sentinel) skips that too and indexes DECIMAL_POWERS / BINARY_POWERS out of bounds, so e.g. filesize(1024, {exponent: -3}) returns "NaN undefined" instead of a sane string, and object output silently drops symbol/unit. Clamp e < 0 to 0 the same way e > 8 is already clamped to 8. --- src/helpers.js | 5 +++++ tests/unit/filesize.test.js | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/helpers.js b/src/helpers.js index 5102a83..56ad7ea 100644 --- a/src/helpers.js +++ b/src/helpers.js @@ -289,6 +289,11 @@ export function calculateExponent(num, e, exponent, isDecimal, precision) { if (e < 0) { e = 0; } + } else if (e < 0) { + // A forced exponent below the auto sentinel (-1) has no meaning and + // would otherwise index the power-of-ten/two lookup tables out of + // bounds (producing NaN). Clamp to 0, mirroring the e > 8 clamp below. + e = 0; } if (e > 8) { diff --git a/tests/unit/filesize.test.js b/tests/unit/filesize.test.js index 035cb46..3e8ac6c 100644 --- a/tests/unit/filesize.test.js +++ b/tests/unit/filesize.test.js @@ -615,6 +615,23 @@ describe("filesize", () => { const result = filesize(1024, { exponent: NaN, standard: "iec" }); assert.strictEqual(result, "1 KiB"); }); + + it("should clamp an out-of-range negative exponent to 0 instead of returning NaN", () => { + // Only -1 is the documented "auto" sentinel. Any other negative exponent + // indexed the power lookup tables out of bounds and produced "NaN undefined". + assert.strictEqual(filesize(1024, { exponent: -2 }), "1024 B"); + assert.strictEqual(filesize(1024, { exponent: -100 }), "1024 B"); + }); + + it("should clamp a negative exponent to 0 for object output", () => { + const result = filesize(1024, { exponent: -3, output: "object" }); + assert.deepStrictEqual(result, { value: 1024, symbol: "B", exponent: 0, unit: "B" }); + }); + + it("should clamp a negative exponent to 0 for array output", () => { + const result = filesize(1024, { exponent: -3, output: "array" }); + assert.deepStrictEqual(result, [1024, "B"]); + }); }); describe("Error handling", () => {