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
15 changes: 15 additions & 0 deletions src/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ export function getBaseConfiguration(standard, base) {
* @param {Object} [localeOptions={}] - Locale formatting options
* @param {string} [separator=""] - Custom decimal separator
* @returns {string|Array|Object|number} Formatted result
* @throws {TypeError} When precision is out of range (1-100) or output is not a supported format
*/
export function handleZeroValue(
precision,
Expand All @@ -96,6 +97,20 @@ export function handleZeroValue(
localeOptions = {},
separator = EMPTY,
) {
// Validate precision and output the same way the non-zero path does, so a
// zero input throws the documented TypeError instead of a raw RangeError
// from toPrecision() or a silently formatted string.
if (
precision > 0 &&
(typeof precision !== "number" || precision < 1 || Math.floor(precision) > 100)
) {
throw new TypeError(INVALID_PRECISION);
}

if (output !== ARRAY && output !== OBJECT && output !== STRING && output !== EXPONENT) {
throw new TypeError(`Invalid output: ${output}`);
}

let value;
if (precision > 0) {
value = (0).toPrecision(precision);
Expand Down
9 changes: 9 additions & 0 deletions tests/unit/filesize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,15 @@ describe("filesize", () => {
assert.throws(() => filesize(1000, { output: "foo" }), TypeError);
});

it("should validate precision and output for zero like any other value", () => {
assert.throws(() => filesize(0, { precision: 101 }), TypeError);
assert.throws(() => filesize(0, { precision: 0.5 }), TypeError);
assert.throws(() => filesize(0, { precision: "3" }), TypeError);
assert.throws(() => filesize(0, { output: "foo" }), TypeError);
assert.throws(() => filesize(0n, { output: "foo" }), TypeError);
assert.strictEqual(filesize(0, { precision: 100.5 }), `0.${"0".repeat(99)} B`);
});

it("should throw TypeError for invalid numeric strings", () => {
assert.throws(() => filesize("1_000"), TypeError);
assert.throws(() => filesize("1000n"), TypeError);
Expand Down