diff --git a/src/printer.js b/src/printer.js index 8d139297..62b5d7df 100644 --- a/src/printer.js +++ b/src/printer.js @@ -641,6 +641,18 @@ function genericPrintNoParens(path, options, print) { if (n.elements.length === 0) { parts.push("[]"); } else { + // JavaScript allows you to have empty elements in an array which + // changes its length based on the number of commas. The algorithm + // is that if the last argument is null, we need to force insert + // a comma to ensure JavaScript recognizes it. + // [,].length === 1 + // [1,].length === 1 + // [1,,].length === 2 + // + // Note that util.getLast returns null if the array is empty, but + // we already check for an empty array just above so we are safe + const needsForcedTrailingComma = util.getLast(n.elements) === null; + parts.push( multilineGroup( concat([ @@ -652,6 +664,7 @@ function genericPrintNoParens(path, options, print) { join(concat([ ",", line ]), path.map(print, "elements")) ]) ), + needsForcedTrailingComma ? "," : "", ifBreak(options.trailingComma ? "," : ""), options.bracketSpacing ? line : softline, "]" diff --git a/tests/arrays/__snapshots__/jsfmt.spec.js.snap b/tests/arrays/__snapshots__/jsfmt.spec.js.snap index 8b9f6b5e..0dd5cc49 100644 --- a/tests/arrays/__snapshots__/jsfmt.spec.js.snap +++ b/tests/arrays/__snapshots__/jsfmt.spec.js.snap @@ -81,6 +81,19 @@ module.exports = \"arrays\"; " `; +exports[`test last.js 1`] = ` +"[,]; +[,,]; +[,,1,]; +[,,1,1]; +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +[ , ]; +[ , , ]; +[ , , 1 ]; +[ , , 1, 1 ]; +" +`; + exports[`test numeric_elem.js 1`] = ` "var arr = []; var day = new Date; diff --git a/tests/arrays/last.js b/tests/arrays/last.js new file mode 100644 index 00000000..12af7b6a --- /dev/null +++ b/tests/arrays/last.js @@ -0,0 +1,4 @@ +[,]; +[,,]; +[,,1,]; +[,,1,1];