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", () => {