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
7 changes: 6 additions & 1 deletion src/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ export const arrayToString: ToString = (array: any[], space, next) => {
})
.join(space ? ",\n" : ",");

// A trailing hole is dropped by an array literal (`[1,]` has length `1`), so
// append a separator to preserve the array length on the round-trip.
const trailingHole =
array.length > 0 && !(array.length - 1 in array) ? "," : "";

const eol = space && values ? "\n" : "";
return `[${eol}${values}${eol}]`;
return `[${eol}${values}${trailingHole}${eol}]`;
};
8 changes: 8 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ describe("javascript-stringify", () => {
describe("arrays", () => {
it("should stringify as array shorthand", test([1, 2, 3], "[1,2,3]"));

it("should preserve a trailing hole", testRoundTrip("[1,,]"));

it("should preserve multiple trailing holes", testRoundTrip("[1,,,]"));

it("should preserve a leading hole", testRoundTrip("[,1]"));

it("should preserve an interior hole", testRoundTrip("[1,,3]"));

it(
"should indent elements",
test([{ x: 10 }], "[\n\t{\n\t\tx: 10\n\t}\n]", "\t"),
Expand Down