[New] add collapseEmpty option #20
Merged
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.
New option to remove newlines in empty arrays and objects
Fixes #15
This PR adds a new option,
collapseEmpty, that can be passed whenstringifyis called. WhencollapseEmptyistrue, empty arrays and empty objects within the output will not have indent characters inserted between their opening and closing brackets. The effect is that the empty brackets will appear next to each other on the same line as their key, even whenspacehas been specified (which otherwise would lead to an indent with the space and a newline).Example from the linked issue: output from
stringify({ a: [], b: {} }, { space: 2 })currently looks like:{ "a": [ ], "b": { } }After these changes,
stringify({ a: [], b: {} }, { collapseEmpty: true, space: 2 })will look like:{ "a": [], "b": {} }collapseEmptyonly matters whenspacehas been specified, since the indent value otherwise is an empty string.TODO: I'm happy to write the README entry for this once you've had a chance to review.
I do think there is a case to be made that this should be the default behavior, in order to maintain the same shape as JSON.stringify when given equivalent options. However, putting this behind a
collapseEmptyoption makes this behavior available without making a breaking change.Note - I had initially checked if
collapseEmptywas true inline in the places where it was needed, but this ran one unit past eslint's complexity threshold for thestringifyfunction. I moved the grouping logic to its own closure to make the linter pass, but am happy to revert and adjust the linting rules instead if that's preferable.Thanks for reviewing this, happy to make any changes!