Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
17 changes: 17 additions & 0 deletions tests/unit/filesize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down