fix: do not throw on a negative number space#65
Open
spokodev wants to merge 1 commit into
Open
Conversation
`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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
stringifythrows on a negative numericspace, whileJSON.stringifytreats any value below 1 as no indentation:It throws for every numeric
spacethat truncates to<= -1(-1,-5,-Infinity).-0.9already works because it truncates toward0, which pins the cause.The README documents the spacer as behaving "the same as with
JSON.stringify()", and ECMA-262JSON.stringifycomputes the gap asmin(10, ToIntegerOrInfinity(space))and uses no indentation for any value< 1— it never throws.Cause
index.js:spaceis clamped to a maximum of 10 but not a minimum of 0, so a negative count reachesString.prototype.repeat, which throws for counts<= -1.Fix
Clamp the lower bound to 0:
Verification
Added a
negative spacer lengthtest asserting equality withJSON.stringifyfor-1,-1e5, and-Infinity. It throws onmainand passes with the fix. Full suite (standard+tap) green.