Skip to content

fix: do not throw on a negative number space#65

Open
spokodev wants to merge 1 commit into
BridgeAR:mainfrom
spokodev:fix-negative-space-no-throw
Open

fix: do not throw on a negative number space#65
spokodev wants to merge 1 commit into
BridgeAR:mainfrom
spokodev:fix-negative-space-no-throw

Conversation

@spokodev

Copy link
Copy Markdown

Problem

stringify throws on a negative numeric space, while JSON.stringify treats any value below 1 as no indentation:

JSON.stringify({ a: 1 }, null, -1)  // '{"a":1}'
stringify({ a: 1 }, null, -1)       // RangeError: Invalid count value: -1

It throws for every numeric space that truncates to <= -1 (-1, -5, -Infinity). -0.9 already works because it truncates toward 0, which pins the cause.

The README documents the spacer as behaving "the same as with JSON.stringify()", and ECMA-262 JSON.stringify computes the gap as min(10, ToIntegerOrInfinity(space)) and uses no indentation for any value < 1 — it never throws.

Cause

index.js:

spacer = ' '.repeat(Math.min(space, 10))

space is clamped to a maximum of 10 but not a minimum of 0, so a negative count reaches String.prototype.repeat, which throws for counts <= -1.

Fix

Clamp the lower bound to 0:

spacer = ' '.repeat(Math.max(0, Math.min(space, 10)))

Verification

Added a negative spacer length test asserting equality with JSON.stringify for -1, -1e5, and -Infinity. It throws on main and passes with the fix. Full suite (standard + tap) green.

`JSON.stringify` treats any numeric `space` below 1 as no indentation, but
`stringify` threw on it:

    JSON.stringify({ a: 1 }, null, -1) // '{"a":1}'
    stringify({ a: 1 }, null, -1)      // RangeError: Invalid count value: -1

The README documents the spacer as behaving "the same as with
JSON.stringify()". `space` was clamped to a maximum of 10 but not a minimum
of 0, so a negative count reached `String.prototype.repeat`, which throws
for counts <= -1. Clamp the lower bound to 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant